This article mainly introduces the C# implementation of the progress bar with percentage function, analyzes the functional requirements of the progress bar with percentage, and provides specific implementation steps and examples in the form of examples For related operation methods, friends in need can refer to
. This article describes the example of C# implementing the progress bar function with percentage. Share it with everyone for your reference, the details are as follows:
Functional requirements:
If a time-consuming calculation process will be performed in the program, I I want a progress bar window to pop up after the user clicks the button to show the progress of the execution (preferably with a percentage). After the execution is completed, the progress bar window closes and returns to the main program window. The parent form cannot be clicked before closing the child window.
Implementation method:
First design the Form2 progress bar form, and put the ProgressBar## in the center of Form2 #ControlprogressBar1 and Label control label1, code:
public partial class Form2 : Form { public Form2(int _Minimum,int _Maximum)//带参数,表示进度条的范围的最小值和最大值 { InitializeComponent(); progressBar1.Maximum=_Maximum;//设置范围最大值 progressBar1.Value = progressBar1.Minimum = _Minimum;//设置范围最小值 } public void setPos(int value)//设置进度条当前进度值 { if (value < progressBar1.Maximum)//如果值有效 { progressBar1.Value = value;//设置进度值 label1.Text = (value * 100 / progressBar1.Maximum).ToString() + "%";//显示百分比 } Application.DoEvents();//重点,必须加上,否则父子窗体都假死 } private void Form2_Load(object sender, EventArgs e) { this.Owner.Enabled = false;//设置父窗体不可用 } private void Form2_FormClosed(object sender, FormClosedEventArgs e) { this.Owner.Enabled = true;//回复父窗体为可用 } }
EventCode:
private void button1_Click(object sender, EventArgs e) { Form2 fm = new Form2(0,100); fm.Show(this);//设置父窗体 for (int i = 0; i < 100; i++) { fm.setPos(i);//设置进度条位置 Thread.Sleep(100);//睡眠时间为100 } fm.Close();//关闭窗体 }
Supplement: Some friends said that fm.Show(this): is not supported in vs2003, then you can add one more parameter to the constructor of From2:
public Form OwnerForm; public Form2(int _Minimum,int _Maximum,Form _OwnerForm)//带参数,表示进度条的范围的最小值和最大值 { InitializeComponent(); progressBar1.Maximum=_Maximum;//设置范围最大值 progressBar1.Value = progressBar1.Minimum = _Minimum;//设置范围最小值 this.OwnerForm=_OwnerForm; } private void Form2_Load(object sender, EventArgs e) { this.OwnerForm.Enabled = false;//设置父窗体不可用 } private void Form2_FormClosed(object sender, FormClosedEventArgs e) { this.OwnerForm.Enabled = true;//回复父窗体为可用 }
private void button1_Click(object sender, EventArgs e) { Form2 fm = new Form2(0,100,this); fm.Show();//设置父窗体 for (int i = 0; i < 100; i++) { fm.setPos(i);//设置进度条位置 Thread.Sleep(100);//睡眠时间为100 } fm.Close();//关闭窗体 }
The above is the detailed content of C# sample code sharing to implement progress bar function with percentage. For more information, please follow other related articles on the PHP Chinese website!