Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a form without showing it

Tags:

c#

winforms

Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:

tasksForm.Visible = false;
tasksForm.Show();

Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.

When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:

tasksForm.WindowState = FormWindowState.Minimized;
tasksForm.Show();

I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.

like image 306
Don Kirkby Avatar asked Sep 15 '08 21:09

Don Kirkby


1 Answers

Perhaps it should be noted here that you can cause the form's window to be created without showing the form. I think there could be legitimate situations for wanting to do this.

Anyway, good design or not, you can do that like this:

MyForm f = new MyForm();
IntPtr dummy = f.Handle; // forces the form Control to be created

I don't think this will cause Form_Load() to be called, but you will be able to call f.Invoke() at this point (which is what I was trying to do when I stumbled upon this SO question).

like image 80
Jeff Roe Avatar answered Oct 12 '22 01:10

Jeff Roe