.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Windows Form Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

WinForms: How to create a control from another thread?

Posted By:Jean Paul       Posted Date: November 02, 2010    Points: 15    Category: Windows Form Controls    URL: http://www.dotnetspark.com  

Creating control from a thread and setting parent to another control which was created in 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";
        }
    }
}

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend