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

后端 未结 7 1917
南笙
南笙 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:21

    You are likely getting to this code before the form has been shown and therefore the window handle has not been created.

    You can add this code before your code and all should be good:

    if (! this.IsHandleCreated)
       this.CreateHandle();
    

    Edit: There's another problem with your code. Once the form is displayed, you cannot call ShowDialog() again. You will get an invalid operation exception. You may want to modify this method as others have proposed.

    You might be better served calling the ShowDialog() directly from the calling class and have another method for BringToFront() or something like that...

提交回复
热议问题