如何在不同的线程上更改Form的窗口状态?

时间:2010-04-08 15:26:32

标签: c# winforms process windowstate

有谁知道如何从另一个线程更改窗体的窗口状态?这是我正在使用的代码:

    private void button4_Click(object sender, EventArgs e)
    {
            string pathe = label1.Text;
            string name = Path.GetFileName(pathe);
            pathe = pathe.Replace(name, "");
            string runpath = label2.Text;
            Process process;
            process = new Process();

            process.EnableRaisingEvents = true;
            process.Exited += new System.EventHandler(process_Exited);

            process.StartInfo.FileName = @runpath;
            process.StartInfo.WorkingDirectory = @pathe;
            process.Start();
            WindowState = FormWindowState.Minimized;
    }
    private void process_Exited(object sender, EventArgs e)
    {
        this.WindowState = FormWindowState.Normal;
    }

这意味着运行程序并最小化,然后在程序关闭后返回正常状态。虽然我收到此错误“跨线程操作无效:控件'Form1'从其创建的线程以外的线程访问。”知道如何让这个工作吗?

5 个答案:

答案 0 :(得分:7)

这适用于.NET 3.5:

Invoke(new Action(() => { this.WindowState = FormWindowState.Normal; }));

或2.0:

Invoke(new MethodInvoker(delegate { this.WindowState = FormWindowState.Normal; }));

答案 1 :(得分:1)

只需在StackOverflow中搜索此字符串“跨线程操作无效”或Google。拜托,不要那么懒。

答案 2 :(得分:1)

请参阅本网站上的What’s the difference between Invoke() and BeginInvoke()。 “选择”的答案很好地解释了你应该做什么。

简而言之,您希望不同的THREADS不会完全创建新流程(或者您不太希望这样做),并且您可能希望使用Invoke()而不是BeginInvoke()这是异步的。

答案 3 :(得分:1)

将此行代码添加到Click事件处理程序:

process.SynchronizingObject = this;

答案 4 :(得分:-1)

这将解决您的问题,将其添加到form_load事件

 System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;