Search code examples
c#.netwinforms.net-2.0

Start a form's message loop without calling show()


I have a System.Windows.Forms.Form window, that needs to get events delivered to it with Control.Invoke(). However, the messages are not getting delivered prior to calling Show() on the form.

In order to work around this, I tried this kludge in the form's constructor:

this.Show();
this.Hide();

This works, and the messages are now getting delivered. However, this results in a window flashing in and out when the form is constructed. Is there a more elegant way to achieve what I want?

I'm working with .NET 2.0 (a newer version is not allowed).


Solution

  • Criterion of Control.Invoke is that Handle has to be created and nothing else. You don't need to call Show and Hide instead force creating the Handle.

    Form yourForm = new Form();
    var handle =  pbForm.Handle;//Force create handle
    

    From this point you can able to call yourForm.Invoke

    Note: Your form's Load event and Shown event will not be fired unless you show the form. So any code depends on those events will break.

    If your code depends on Load or Shown events, you need a hack. You need to make the form very small so that user can't notice it (Probably size of 1,1), then call Show and Hide. Later at some point when you need to show the form to user you can set a decent Size.