81

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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Pondidum
  • 11,457
  • 8
  • 50
  • 69

25 Answers25

119

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;                
    }
}
Paul Aicher
  • 1,191
  • 1
  • 7
  • 2
  • 2
    Thanks! Unlike nearly all of the other suggestions here, this one does NOT show a brief flash of the main window. – Andy Jan 06 '11 at 10:38
  • 2
    This is the actual correct way to do this, so it should be the accepted answer. Back in the MFC days we used to do a similar thing where we would handle the first WM_WINDOWPOSCHANGING message and hide the form there to prevent "window flashing". – enriquein Sep 28 '11 at 02:15
  • Thanks I tried the accepted answer and it didn't work as I need to show a tray Icon, this however worked perfectly. – Omar Kooheji Apr 17 '12 at 15:48
  • This works, but I think @Jeff's answer is better since it doesn't require an override with some logic hacking. – Mark Lakata Jul 18 '13 at 18:10
  • For me this affects somehow the threading model behind: one of my worker threads ended up creating some UI controls which is completely wrong... so I must skip this solution. – Learner Dec 16 '13 at 09:37
  • 1
    Unfortunately, the notify icon doesn't appear at all when I add the SetVisibleCore() method to the form, so I can't get it to show with a mouse click afterwards. – Dan W Mar 14 '15 at 11:40
  • Is there a way to combine this with a timer? When I try to set the form back to visible from within a `System.Threading.TimerCallback`, the app locks up – Ben Philipp Apr 02 '16 at 02:58
  • How do you learn so much about how the .net framework works at it's core to the point that this is something you know?? Not rhetorical question. – BinkyNichols Sep 03 '19 at 18:54
  • Perfect. As others have stated this doesn't show a flash and works perfect on Windows 7 and 10. – Cody J. Mathis Nov 27 '19 at 22:36
  • Be aware that `Form_Load` will not be called until the form is shown at first time. – tigrou Mar 14 '22 at 22:25
117

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.

Thick_propheT
  • 1,003
  • 2
  • 10
  • 29
Grokys
  • 16,228
  • 14
  • 69
  • 101
  • 15
    By far and away the best (and one of the simplest) solutions I've seen. All the garbage about setting opacity to zero, having separate Timer instances to hide the form etc have code smell for days. – nathanchere Mar 12 '10 at 00:26
  • Using this method, will it still be found by `Process.MainWindowHandle` and the like? – Sebastian Sep 16 '13 at 10:07
  • 13
    The designer doesn't have a Visible property as far as I can see. – Dan W Mar 14 '15 at 11:41
  • `Application.Run()` on .NET 3.5 Compact requires one parameter (a form) – Dayan Jun 18 '15 at 13:31
  • @Benny Oh yes it does work perfectly. You might want to state why you did so you could get some help but it certainly work. – Ahmed salah Sep 17 '15 at 17:34
  • 5
    Visual Studio 2015 and .NET 4.5 here... Designer has no `visible` property for forms. Am I overlooking something? – Ben Philipp Apr 02 '16 at 01:42
  • There is a Visible property in code, so you could set it in the Form's constructor. – Steve Smith Jan 11 '17 at 12:38
  • 1
    correct me if I am wrong, the Application.Run provides the process with a message loop needed for windows forms. Without it your code inside your form will then crash. – manit Aug 24 '17 at 18:12
  • 4
    Be aware that in this case `Form_Load` will not be called until the form is shown at first time. And may be never. Also closing the main form will not close the application. You have to use `Application.Exit`. – rattler Feb 22 '19 at 15:22
39

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.

Tute
  • 6,943
  • 12
  • 51
  • 61
  • 3
    This causes the program to flash on and then quickly hide on startup. – Dan W Mar 14 '15 at 11:44
  • I guess i should do so much if i wouldn't see your code . Thanks – M at Jul 19 '16 at 13:06
  • To address the flash at app startup, set the Form Opacity to 0 in the designer, then in the callback, call Hide() first and then set Opacity back to 100. – Michael Bray Aug 06 '16 at 03:27
21
    protected override void OnLoad(EventArgs e)
    {
        Visible = false; // Hide form window.
        ShowInTaskbar = false; // Remove from taskbar.
        Opacity = 0;

        base.OnLoad(e);
    }
Chriz
  • 572
  • 7
  • 14
16

At form construction time (Designer, program Main, or Form constructor, depending on your goals),

 this.WindowState = FormWindowState.Minimized;
 this.ShowInTaskbar = false;

When you need to show the form, presumably on event from your NotifyIcon, reverse as necessary,

 if (!this.ShowInTaskbar)
    this.ShowInTaskbar = true;

 if (this.WindowState == FormWindowState.Minimized)
    this.WindowState = FormWindowState.Normal;

Successive show/hide events can more simply use the Form's Visible property or Show/Hide methods.

Jeff
  • 161
  • 1
  • 2
6

Try to hide the app from the task bar as well.

To do that please use this code.

  protected override void OnLoad(EventArgs e)
  {
   Visible = false; // Hide form window.
   ShowInTaskbar = false; // Remove from taskbar.
   Opacity = 0;

   base.OnLoad(e);
   }

Thanks. Ruhul

5

Extend your main form with this one:

using System.Windows.Forms;

namespace HideWindows
{
    public class HideForm : Form
    {
        public HideForm()
        {
            Opacity = 0;
            ShowInTaskbar = false;
        }

        public new void Show()
        {
            Opacity = 100;
            ShowInTaskbar = true;

            Show(this);
        }
    }
}

For example:

namespace HideWindows
{
    public partial class Form1 : HideForm
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

More info in this article (spanish):

http://codelogik.net/2008/12/30/primer-form-oculto/

3

I have struggled with this issue a lot and the solution is much simpler than i though. I first tried all the suggestions here but then i was not satisfied with the result and investigated it a little more. I found that if I add the:

 this.visible=false;
 /* to the InitializeComponent() code just before the */
 this.Load += new System.EventHandler(this.DebugOnOff_Load);

It is working just fine. but I wanted a more simple solution and it turn out that if you add the:

this.visible=false;
/* to the start of the load event, you get a
simple perfect working solution :) */ 
private void
DebugOnOff_Load(object sender, EventArgs e)
{
this.Visible = false;
}
Abdul Rahman
  • 2,097
  • 4
  • 28
  • 36
echoen
  • 31
  • 1
3

You're going to want to set the window state to minimized, and show in taskbar to false. Then at the end of your forms Load set window state to maximized and show in taskbar to true

    public frmMain()
    {
        Program.MainForm = this;
        InitializeComponent();

        this.WindowState = FormWindowState.Minimized;
        this.ShowInTaskbar = false;
    }

private void frmMain_Load(object sender, EventArgs e)
    {
        //Do heavy things here

        //At the end do this
        this.WindowState = FormWindowState.Maximized;
        this.ShowInTaskbar = true;
    }
George
  • 41
  • 3
3

Put this in your Program.cs:

FormName FormName = new FormName ();

FormName.ShowInTaskbar = false;
FormName.Opacity = 0;
FormName.Show();
FormName.Hide();

Use this when you want to display the form:

var principalForm = Application.OpenForms.OfType<FormName>().Single();
principalForm.ShowInTaskbar = true;
principalForm.Opacity = 100;
principalForm.Show();
Plague
  • 51
  • 6
1

This works perfectly for me:

[STAThread]
    static void Main()
    {
        try
        {
            frmBase frm = new frmBase();               
            Application.Run();
        }

When I launch the project, everything was hidden including in the taskbar unless I need to show it..

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
1

Override OnVisibleChanged in Form

protected override void OnVisibleChanged(EventArgs e)
{
    this.Visible = false;

    base.OnVisibleChanged(e);
}

You can add trigger if you may need to show it at some point

public partial class MainForm : Form
{
public bool hideForm = true;
...
public MainForm (bool hideForm)
    {
        this.hideForm = hideForm;
        InitializeComponent();
    }
...
protected override void OnVisibleChanged(EventArgs e)
    {
        if (this.hideForm)
            this.Visible = false;

        base.OnVisibleChanged(e);
    }
...
}
LKane
  • 11
  • 1
1
    static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Form1 form1 = new Form1();
            form1.Visible = false;
            Application.Run();

        }
 private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }
0
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    MainUIForm mainUiForm = new MainUIForm();
    mainUiForm.Visible = false;
    Application.Run();
}
j0k
  • 22,600
  • 28
  • 79
  • 90
kilsek
  • 48
  • 6
0

This example supports total invisibility as well as only NotifyIcon in the System tray and no clicks and much more.

More here: http://code.msdn.microsoft.com/TheNotifyIconExample

0

As a complement to Groky's response (which is actually the best response by far in my perspective) we could also mention the ApplicationContext class, which allows also (as it's shown in the article's sample) the ability to open two (or even more) Forms on application startup, and control the application lifetime with all of them.

Community
  • 1
  • 1
Eugenio Miró
  • 2,398
  • 2
  • 28
  • 38
0

I had an issue similar to the poster's where the code to hide the form in the form_Load event was firing before the form was completely done loading, making the Hide() method fail (not crashing, just wasn't working as expected).

The other answers are great and work but I've found that in general, the form_Load event often has such issues and what you want to put in there can easily go in the constructor or the form_Shown event.

Anyways, when I moved that same code that checks some things then hides the form when its not needed (a login form when single sign on fails), its worked as expected.

blind Skwirl
  • 321
  • 3
  • 6
0

Launching an app without a form means you're going to have to manage the application startup/shutdown yourself.

Starting the form off invisible is a better option.

Roger Willcocks
  • 1,649
  • 13
  • 27
0

I use WindowState as Minimized for FormMain in designer.

And in FormMain_Load use Hide();

this way when closing the formMain the app exits because I put it in:

Application.Run(formMain = new FormMain());

And notifyIconMain is set as Visible in designer.

And:

       private void notifyIconMain_MouseDoubleClick(object sender, MouseEventArgs e)
                {
                    Show();
                    WindowState = FormWindowState.Normal;
                    //notifyIconMain.Visible = false;
                }
        
        private void buttonHideToTray_Click(object sender, EventArgs e)
                {
                    Hide();
                    //notifyIconMain.Visible = true;
                }

If you want to hide the notifyIconMain from system tray when the form is shown then uncomment the 2 lines in the block of code above.

John1990
  • 29
  • 1
  • 7
0

This worked for me:

protected override void SetVisibleCore(bool value)
{
    if (!this.IsHandleCreated)
    {
        this.CreateHandle();
        value = false;
    }

    base.SetVisibleCore(value);
}
-1

Here is a simple approach:
It's in C# (I don't have VB compiler at the moment)

public Form1()
{
    InitializeComponent();
    Hide(); // Also Visible = false can be used
}

private void Form1_Load(object sender, EventArgs e)
{
    Thread.Sleep(10000);
    Show(); // Or visible = true;
}
aku
  • 122,288
  • 32
  • 173
  • 203
-2

Based on various suggestions, all I had to do was this:

To hide the form:

Me.Opacity = 0
Me.ShowInTaskbar = false

To show the form:

Me.Opacity = 100
Me.ShowInTaskbar = true
sth
  • 222,467
  • 53
  • 283
  • 367
Jon Onstott
  • 13,499
  • 16
  • 80
  • 133
-2

In the designer, set the form's Visible property to false. Then avoid calling Show() until you need it.

A better paradigm is to not create an instance of the form until you need it.

deemer
  • 1,142
  • 8
  • 10
-3

I do it like this - from my point of view the easiest way:

set the form's 'StartPosition' to 'Manual', and add this to the form's designer:

Private Sub InitializeComponent()
.
.
.
Me.Location=New Point(-2000,-2000)
.
.
.
End Sub

Make sure that the location is set to something beyond or below the screen's dimensions. Later, when you want to show the form, set the Location to something within the screen's dimensions.

steve_k
  • 1
  • 1
-3

Why do it like that at all?

Why not just start like a console app and show the form when necessary? There's nothing but a few references separating a console app from a forms app.

No need in being greedy and taking the memory needed for the form when you may not even need it.

Benjamin Autin
  • 4,143
  • 26
  • 34