Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

WinForms: How to create a control from another thread?

Posted by Paul on October 28, 2010


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";

        }

    }

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s