C#从另一个线程调用form.show()在安装程序中不起作用



在我的c#windows应用程序中,我想在由线程检查的条件下显示另一个表单。并且该(第二)线程已经被另一(第一)线程调用。以下是我用来更好解释的代码:

主要方法:

static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

Form1方法:

private void Form1_Load(object sender, EventArgs e)
{
        // Call First thread to start background jobs.
        var thread = new Thread(ThreadFirst);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        // Continue my load event stuff here...
}
    private void ThreadFirst()
    {
        // Do some background operations..
        // Call second thread to switch to another background process.
        var thread = new Thread(ThreadSecond);
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
}
private void ThreadSecond()
{
        If (condition)
                // navigate to another form and close running one..
                ShowAnotherForm();
        else
        {
                // Continue working on current form.
        }
}
[STAThread]
private void ShowAnotherForm()
{
     try
     {
           // Object for new form.
           globalForm = new myForm();
           globalForm.Show();
           // Close the current form running..
           this.Close();
           this.ShowInTaskbar = false;
           Application.Run();           
     }
     catch (Exception ex)
     {
           messagebox.Show(ex.message);
     }
}

当我从我的解决方案中运行这个时,它是完美的。但是,当我为此创建msi包时,这两种形式都被隐藏了。我是不是错过了一些可以添加到其中的东西,这样它也可以从设置中正常工作?

谢谢。

您不应该在"非GUI"线程上调用"GUI Stuff"。所有的GUI调用都应该在GUI线程上。使用InvokeRequiredInvoke确保所有GUI代码都在正确的线程上完成。谷歌会给你举很多例子。

最新更新