Single Form Hide on Startup
I have an application with one form in it, and on the Load method I need to hide the form.
The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.
Any suggestions?
Solution 1:
I'm coming at this from C#, but should be very similar in vb.net.
In your main program file, in the Main method, you will have something like:
Application.Run(new MainForm());
This creates a new main form and limits the lifetime of the application to the lifetime of the main form.
However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.
Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling Form.Show()
or Form.Hide()
from handlers of NotifyIcon events will show and hide the form respectively.
Solution 2:
Usually you would only be doing this when you are using a tray icon or some other method to display the form later, but it will work nicely even if you never display your main form.
Create a bool in your Form class that is defaulted to false:
private bool allowshowdisplay = false;
Then override the SetVisibleCore method
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(allowshowdisplay ? value : allowshowdisplay);
}
Because Application.Run() sets the forms .Visible = true after it loads the form this will intercept that and set it to false. In the above case, it will always set it to false until you enable it by setting allowshowdisplay to true.
Now that will keep the form from displaying on startup, now you need to re-enable the SetVisibleCore to function properly by setting the allowshowdisplay = true. You will want to do this on whatever user interface function that displays the form. In my example it is the left click event in my notiyicon object:
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
this.allowshowdisplay = true;
this.Visible = !this.Visible;
}
}
Solution 3:
I use this:
private void MainForm_Load(object sender, EventArgs e)
{
if (Settings.Instance.HideAtStartup)
{
BeginInvoke(new MethodInvoker(delegate
{
Hide();
}));
}
}
Obviously you have to change the if condition with yours.