C# Tips

Today's C# Tip

When Control.Invoke() is called before window handle is created

Problem

One of my blog readers asked why he was unable to call Control.Invoke() in Form constuctor. Calling Invoke() method in Form constructor (or after form is closed/disposed) causes an error "Invoke or BeginInvoke cannot be called on a control until the window handle has been created."

	public Form1()
	{
		InitializeComponent();

		// Error
		this.button1.Invoke((MethodInvoker)delegate
		{
			this.button1.Text = "OK";
		});
	}

 

Solution

Invoke or BeginInvoke method can be called on a control when the control has window handle. Window handles for the child controls are created after Form is loaded/shown. So the fix is to move the code in Form_Load event handler or somewhere after the window handle is created.

	public Form1()
	{
		InitializeComponent();
	}

	private void Form1_Load(object sender, EventArgs e)
	{
		// No Error
		this.button1.Invoke((MethodInvoker)delegate
		{
			this.button1.Text = "OK";
		});
	}

 

By the way, there is no reason to use Invoke() method in the example above. This is for illustration purpose only.