如何关注从不同线程启动的Dialog? [英] How do I give focus to a Dialog started from a different thread?

查看:83
本文介绍了如何关注从不同线程启动的Dialog?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能有点像一个新手问题,但我有一个问题,让焦点在一个单独的线程上的对话框。一个简单的例子如下:

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:

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();
		}
	}
}





单击按钮1会创建对话框,按钮2会尝试给予关注。但是我得到异常{跨线程操作无效:控制''从其创建的线程以外的线程访问。}



现在我得到这个,但我似乎无法找到解决办法。我曾尝试使用AttachThreadInput和互联网上描述的各种其他方法,但无济于事。



帮助赞赏。



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.

推荐答案

Form2 的UI线程上调用它,就像这样;

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



此外,我将 .Focus 更改为 .Activate 因为我认为这就是你真正想要的,但我可能错了:)



希望这会有所帮助,

Fredrik


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


无法在与UI(启动)线程不同的线程上创建对话框。您将遇到对话框的问题。



如果您希望它们能够100%正常工作,则必须在UI(启动)线程上创建所有UI元素时间。当然,你可以尝试它,它可能在您的DEV机器上有点工作,但它不会持续。如果您创建或触摸其他线程中的UI元素,您将遇到无法在计算机上复制的细微问题。
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.


这篇关于如何关注从不同线程启动的Dialog?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆