【问题标题】:call Invoke method from a custom class从自定义类调用 Invoke 方法
【发布时间】:2010-12-16 18:15:02
【问题描述】:

我遇到了这样的问题

My form doesn't properly display when it is launched from another thread

现在我的问题是如何从自定义类而不是表单调用 Invoke 方法

void call_thread()
    {

        Thread t = new Thread(new ThreadStart(this.ShowForm1));
        t.Start();

    }

 delegate void Func();
    private void ShowForm1()
    {            
        if (this.InvokeRequired) //error
        {
            Func f = new Func(ShowForm1);
            this.Invoke(f); //error
        }
        else
        {
            Form1 form1 = new Form1();
            form1.Show();
        }            
    }

【问题讨论】:

    标签: c#


    【解决方案1】:

    你不能。 Invoke 特定于 Winforms 控件,因为它会将消息输入 Windows 消息泵以执行您需要执行的任何操作。因此,在您的自定义类中,显然没有消息泵,这是无法做到的。

    【讨论】:

      【解决方案2】:

      我得到了答案

      在线程中我可以调用 form1.ShowDialog();它没有显示为对话框,因为它在另一个线程中

      新代码是

      void call_thread()
          {
      
              Thread t = new Thread(new ThreadStart(this.ShowForm1));
              t.Start();
      
          }
      
          private void ShowForm1()
          {            
                 Form1 form1 = new Form1();
                  form1.ShowDialog();
      
          }
      

      【讨论】:

      • 您还必须插入 t.SetApartmentState(ApartmentState.STA) 否则很多东西将无法正常工作(剪贴板、shell 对话框、拖放)。
      猜你喜欢
      • 2023-03-27
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多