tags:

views:

315

answers:

2

I need to make a button focus at the end of a thread. The Button.Focus() method does not seem to work.

for exmaple:

Button1_Click(object sender, EventArgs e)
{
   Thread myThread = new Thread(theThread);
   myThread.Start();
}

theThread()
{
  ... 
  Button2.Focus(); // does not seem to focus the button
}

However, if I put Button2.Focus() in Button1_Click it will focus, but for my project I can't do that.

+1  A: 

Any UI changes have to be made from the form's main thread. Look into calling the form's "Invoke" method from your own thread. You'll want to pass "Invoke" a delegate to a method that calls the "Focus" method on your button.

David
+3  A: 

For a generic solution to these kind of problems, take a look at SyncronizationContext class. For Windows forms, however, you could use the Invoke method and in WPF, you could use Dispatcher.Invoke:

//WinForms:
Invoke(delegate{ Button2.Focus(); });
Mehrdad Afshari