WinForms: How to create a control from another thread?

Control.CheckForIllegalCrossThreadCalls = false; is needed for refreshing controsl from other threads.

But for creating controls and setting parent to other control which was created in another thread the following code is needed.

Pre-requisites

Create a new windows forms application and place a button with click event handler on it.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Threading;

 

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        public delegate void DelegateDefinition();

 

        private void button1_Click(object sender, EventArgs e)

        { 

            DelegateDefinition delgate = new DelegateDefinition(CreateButton);

            ThreadStart threadStart = new ThreadStart(delegate { this.BeginInvoke(delgate); });

            Thread thread = new Thread(threadStart);

            thread.Start();

        }

 

        public void CreateButton()

        {

            Button button = new Button();

            button.Parent = this;

            button.Location = new Point(10, 10);

            button.Size = new Size(200, 25);

            button.Text = "Hi! I am the new button";

        }

    }

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *