InvokeRequired of Form == false and InvokeRequired of contained control == true

前端 未结 3 524
离开以前
离开以前 2021-01-12 12:11

how is it possible? I have windows Form control, derived from System.Windows.Forms.Form with WebBrowser control contained in this form. Webbrowser object instance is created

3条回答
  •  Happy的楠姐
    2021-01-12 13:06

    I've been investigating this same weird behaviour. I need to operate some controls from different threads (e.g. show information about a device that is connected to the host or trigger actions depending on different devices states).

    This link gave me a good hint: http://csharpfeeds.com/post/2898/Control.Trifecta_InvokeRequired_IsHandleCreated_and_IsDisposed.aspx

    I still don't know how MS people intended to make use of their own stuff (and don't agree in many aspects), but, in one application I had to make the following dirty and filthy workaround:

    • Create the control/form in the main thread (make sure it is the main thread).
    • In the same procedure, check the control Handle. This simple check will force it to be created and in the right thread!

    How ugly, isn't? I'd like to know if anyone else has a better way to do it.

    _my_control = new ControlClass( );
    _my_control.Owner = this;
    
    IntPtr hnd;
    
    // Force Handle creation by reading it.
    if ( !_my_control.IsHandleCreated || _my_control.Handle == IntPtr.Zero )
        hnd = _my_control.Handle;
    

    (Sorry for posting in this somewhat old post, but I just thought it could be usefull to someone).

提交回复
热议问题