Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
4.33/5 (2 votes)
See more:
Probably a bit of a novice question, but I'm having a problem giving focus to a dialog which is on a separate thread. A simple example is below:
C#
namespace Playtime
{
        public partial class Form1 : Form
        {
		public Form1()
		{
			InitializeComponent();
		}

		Thread th;
		Form2 f2;

		private void button1_Click(object sender, EventArgs e)
		{
			th = new Thread(() => DoThread());
			th.Start();
		}

		void DoThread()
		{
			f2 = new Form2();
			f2.ShowDialog();
			f2.Dispose();
		}

		private void button2_Click(object sender, EventArgs e)
		{
			f2.Focus();
		}
	}
}


Button 1 when clicked creates the dialog and button 2 attempts to give it focus. However I get the exception {"Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on."}

Now I get this, but I can't seem to find a way around it. I have tried using AttachThreadInput and various other methods described on the internet but to no avail.

Help appreciated.
Posted
Updated 3-Sep-14 1:44am
v2

Invoke it on the UI-thread of Form2, like this;
C#
private void button2_Click(object sender, EventArgs e)
{
    f2.Invoke(new Action(delegate {
        f2.Activate();
    }));
}

Also, I changed .Focus to .Activate because I think that's what you're really after, but I might be wrong :)

Hope this helps,
Fredrik
 
Share this answer
 
Comments
Badger Roj 3-Sep-14 8:00am    
That's the ticket! Thanks very much .. and I did mean Activate :-)
Fredrik Bornander 3-Sep-14 8:06am    
Glad I could help.
The dialog cannot be created on a different thread than the UI (startup) thread. You ARE going to run into problems with the dialog.

ALL UI elements must be created on the UI (startup) thread if you expect them to work properly 100% of the time. Sure, you can try it and it may work for a bit on your DEV machine, but it won't last. You WILL run into subtle problems that you can't duplicate on your machine if you create or touch UI elements from other threads.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900