Pattern - Form OnClick

Open Visual Studio 2022 as Administrator.
Create a New Project, language C#, platform Windows, project type Desktop.
Find "Windows Forms App" and press Next
Change the Project Name to "WinForms_Threading_BWOnClick".
Check / change the Location if necessary.
Press Next.
Check / Change the Framework to .NET 6.0.
Press Create.
This will create a solution that contains two projects

Create a Windows Form called "UsingThread"
On the Windows Form add two buttons and text box
You can only update the UI from the UI thread.
Add the following code

public partial class UsingThread : System.Windows.Forms.Form 
    public delegate void UpdateTextBox(string label);
    public bool isRunning { get; set; }

    public UsingThread()

    public void UpdateUI(string labelText)
        this.txtStatusBox.Text = labelText + System.Environment.NewLine + this.txtStatusBox.Text;

    private void btnStop_Click(object sender, EventArgs e)
       isRunning = false;

    private void btnStart_Click(object sender, EventArgs e)
        System.DateTime startTime = System.DateTime.Now;
        isRunning = true;

        System.Threading.Thread t = new System.Threading.Thread(() =>
            while (isRunning == true)
                string timeElapsedInString = (System.DateTime.Now - startTime).ToString(@"hh\:mm\:ss");
                this.txtStatusBox.Invoke(new UpdateTextBox(UpdateUI), timeElapsedInString);



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext