What's wrong with my cross-thread call in Windows Forms?

后端 未结 7 1896
南笙
南笙 2021-01-04 22:32

I encounter a problem with a Windows Forms application.

A form must be displayed from another thread. So in the form class, I have the following code:



        
7条回答
  •  北海茫月
    2021-01-04 23:11

    Try this one:

    private delegate void DisplayDialogCallback();
    
    public void DisplayDialog()
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new DisplayDialogCallback(DisplayDialog));
        }
        else
        {
            if (this.Handle != (IntPtr)0) // you can also use: this.IsHandleCreated
            {
                this.ShowDialog();
    
                if (this.CanFocus)
                {
                    this.Focus();
                }
            }
            else
            {
                // Handle the error
            }
        }
    }
    

    Please note that InvokeRequired returns

    true if the control's Handle was created on a different thread than the calling thread (indicating that you must make calls to the control through an invoke method); otherwise, false.

    and therefore, if the control has not been created, the return value will be false!

提交回复
热议问题