[to] implement Winfrom progress bar and progress information tips, WINFROM program suspended animation processing

Source: Internet
Author: User
Tags close page

China_xuhua Original Address

1. Method One: Using threads

Function Description: In the process of winfrom development with C #. We often need to use a progress bar (ProgressBar) to display progress information. At this point we may need to use multi-threading, If you do not use multithreading control progress bar, the window is easy to feign death (unable to see the progress information in a timely manner). Below I will simply combine an example I wrote to give you an introduction.

The first step : Design The interface, note the need to refer to using System.Threading;

The control names are: Progressbar1;label1;textbox1;button1;
Step Two: Defines a proxy that updates the value of the ProgressBar and returns the processing information of the method when the method is executed.

Private delegate void SetPos (int ipos,string vinfo);//Agent

Step three : progress bar value update function (parameters must be the same as declared proxy parameters)

private void Settextmesssage (int ipos,string vinfo)        {            if (this. invokerequired)            {                SetPos SetPos = new SetPos (settextmesssage);                This. Invoke (SetPos, new object[] {ipos,vinfo});            }            else            {                This.label1.Text = IPOs. ToString () + "/1000";                This.progressBar1.Value = Convert.ToInt32 (IPOs);                This.textBox1.AppendText (Vinfo);            }        }

Fourth Step: function implementation

private void Button1_Click (object sender, EventArgs e)        {            Thread fthread = new Thread (new ThreadStart (sleept));            Fthread.start ();        }

Fifth step: The new thread execution function:

private void Sleept ()        {for            (int i = 0; i <; i++)            {                System.Threading.Thread.Sleep (ten);                Settextmesssage (100*i/500,i.tostring () + "\ r \ n");}        }

Program run:

========================================================================================= 2, The second method features a description: This method is implemented through the control BackgroundWorker1, the progress bar. But the progress bar is in a template window body. First step: main Form Design:

Control Name:

Button1;backgroundworker1;

For the BackgroundWorker1 control, set the property:

The second step: Main Page background code:

Using system.threading;//reference space name private void Button1_Click (object sender, EventArgs e) {This.bac Kgroundworker1.runworkerasync (); Run the BackgroundWorker component processform form = new ProcessForm (this.backgroundworker1);//Show progress bar forms form .            ShowDialog (this); Form.        Close ();            private void Backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e) {            if (e.error! = null) {MessageBox.Show (e.error.message); } else if (e.cancelled) {} else {}}//You        You can implement your calls, methods, and so on within this method. private void Backgroundworker1_dowork (object sender, DoWorkEventArgs e) {BackgroundWorker worker = Send            ER as BackgroundWorker;                for (int i = 0; i < i++) {thread.sleep (100); Worker.                ReportProgress (i); if (worker.                    cancellationpending)//If the user cancels out the processing data code {E.cancel = true;                Break }            }        }

Select the events for the button control and the BackgroundWorker1 control, respectively.

Step three: Set up the subform (and the form that displays the progress bar):

Control Name: Progressbar1;button1 Fourth Step: Subform, Background code:

Private BackgroundWorker BackgroundWorker1; ProcessForm Form event (progress bar form) public processform (BackgroundWorker backgroundWorker1) {Initializecomp            Onent ();            This.backgroundworker1 = BackgroundWorker1;            This.backgroundWorker1.ProgressChanged + = new Progresschangedeventhandler (backgroundworker1_progresschanged); this.backgroundWorker1.RunWorkerCompleted + = new Runworkercompletedeventhandler (backgroundworker1_        runworkercompleted); } void Backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e) {//thi         S.close ();//after execution, directly close page} void backgroundworker1_progresschanged (object sender, ProgressChangedEventArgs e)        {this.progressBar1.Value = E.progresspercentage;            } private void Button1_Click (object sender, EventArgs e) {this.backgroundWorker1.CancelAsync ();            this.button1.Enabled = false; This.     Close ();   }    } 

Select events for Button only.

The execution effect is:

3. The third method:

Function Description: When processing a large amount of data, sometimes the execution of the method takes a certain amount of time, which often results in the "suspended animation" state of the page or program, and the experience of the user is not very good. In order to avoid "suspended animation" to improve the user's experience, here for this type of method adds a progress bar and a text box, the progress bar is used to show the progress of the program processing, the text box is used to display in the process, give a hint. This method mainly uses the control: backgroundWorker1; Description: This method and the above method (method two) basic type, mainly is the design and the code has made some modifications.


First step: main Form Design:

Control Name:

Button1;backgroundworker1;

For the BackgroundWorker1 control, set the property:


Step two: main form background code:

private void Button1_Click (object sender, EventArgs e) {this.backgroundWorker1.RunWorkerAsync ();//Run BackgroundWorker components ProcessForm form = new ProcessForm (this.backgroundworker1);//Show progress bar form forms.            ShowDialog (this); Form.        Close ();            private void Backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e) {            if (e.error! = null) {MessageBox.Show (e.error.message); } else if (e.cancelled) {} else {}}//You        You can implement your calls, methods, and so on within this method. private void Backgroundworker1_dowork (object sender, DoWorkEventArgs e) {BackgroundWorker worker = Send            ER as BackgroundWorker;                for (int i = 0; i < i++) {thread.sleep (100); Worker. ReportProgress (i, i.tostring () + "Hello!" \ r \ n "); Note: This returns the information value to the subform, which is two values, one for the progress bar, and one forof the text box. if (worker.                    cancellationpending)//If the user cancels out the processing data code {E.cancel = true;                Break }            }        }

Step three: Set up the subform (and the form that displays the progress bar):

Control:

Progressbar1;textbox1;button1

Fourth Step: Sub-form background code:

 Private BackgroundWorker BackgroundWorker1; ProcessForm Form event (progress bar form) public processform (BackgroundWorker backgroundWorker1) {Initializecomp            Onent ();            This.backgroundworker1 = BackgroundWorker1;            This.backgroundWorker1.ProgressChanged + = new Progresschangedeventhandler (backgroundworker1_progresschanged); this.backgroundWorker1.RunWorkerCompleted + = new Runworkercompletedeventhandler (backgroundworker1_        runworkercompleted); } void Backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e) {//thi         S.close ();//after execution, directly close page} void backgroundworker1_progresschanged (object sender, ProgressChangedEventArgs e)            {this.progressBar1.Value = E.progresspercentage; This.textBox1.AppendText (E.userstate.tostring ());//The main form passes over the value, through E. Userstate.tostring () to accept} private void Button1_Click (object sender, EventArgs e) {this.ba CKgroundworker1.cancelasync ();            this.button1.Enabled = false; This.        Close (); }

The effect of the implementation:

Note: If the program is executed, click Cancel, it is likely to error, this time, you will modify a method: backgroundworker1_progresschanged: void backgroundworker1_ ProgressChanged (object sender, ProgressChangedEventArgs e)
{
This.progressBar1.Value = E.progresspercentage;
This.textBox1.Text + = e.userstate.tostring (); The main form passes over the value, through E. Userstate.tostring () to accept
       }       This method, replace it with the method above, it is possible.  4, Fourth method:      function Description: This method realizes the progress bar display, the method executes the information feedback display. The technical points used are threads and proxies.          Step One: Add the Main page.         Control Name:button1;   Step two: Main Page background Code         
The using system.threading;//references this naming//creation agent. Private FORM6 Myprocessbar = null;//popup (used to display the progress bar) Private delegate bool Increasehandle (int nvalue,string vinfo); /proxy creates private increasehandle Myincrease = null;//claims proxy, used for subsequent instantiation of proxy private int vMax = 100;//for instantiating progress bar, can be based on your own needs , self change private void Button1_Click (object sender, EventArgs e) {thread thdsub = new Thread (new Th            Readstart (Threadfun));        Thdsub.start ();            } private void Threadfun () {MethodInvoker mi = new MethodInvoker (Showprocessbar); This.            BeginInvoke (MI);            Thread.Sleep (100);            Object objreturn = null; for (int i = 0; i < VMax; i++) {Objreturn = this.                Invoke (This.myincrease, new object[] {2, i.tostring () + "\ r \ n"});            Thread.Sleep (50);            }} private void Showprocessbar () {Myprocessbar = new FORM6 (VMAX); MyINcrease = new Increasehandle (myprocessbar.increase);            Myprocessbar.showdialog ();        Myprocessbar = null; }

Step three: Create a subform control name: Progressbar1;textbox1 Step Four: subform, background code
 Public Form6 (int vMax) {InitializeComponent ();        This.progressBar1.Maximum = VMax;                } public bool Increase (int nvalue,string ninfo) {if (Nvalue > 0) { if (progressBar1.Value + Nvalue < Progressbar1.maximum) {progressBar1.Value + = Nvalu                    E                    This.textBox1.AppendText (Ninfo);                    Application.doevents ();                    Progressbar1.update ();                    Progressbar1.refresh ();                    This.textBox1.Update ();                    This.textBox1.Refresh ();                return true;                    } else {progressbar1.value = Progressbar1.maximum;                    This.textBox1.AppendText (Ninfo); This.                Close ();//after execution, automatically close the subform return false;        }} return false; }
Execution effect:

[to] implement Winfrom progress bar and progress information tips, WINFROM program suspended animation processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.