VB.Net - Hide Form at Startup

I’ve been using Microsoft Visual Basic 2008 (Express Edition) recently to create some utilities.  As part of this I needed to have an application start-up but only display as an icon in the system tray.  After attaching a notify icon control to my main form I set the form’s load method to set the display in task bar and visible properties of the form to be false.

Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles 
    MyBase.Load
    notifyiconMain.Visible = True
    Me.WindowState = FormWindowState.Minimized
    Me.Visible = False
End Sub

However this code doesn’t have quite the effect you think it should - i.e. hiding the form and displaying the icon in the system tray.  What in fact happens (at least on Windows XP) is the window is squished up next to the start menu (the icon in the system tray is also there - as we would want).

These few lines of code work fine once the form is created and displayed, so the issue is definitely linked to the initial creation of the form.

After trying several options (such as minimise, restore, minimise) I succumbed to Googling for an answer and whilst I found lots of answers they were all complicated, a little laborious or just bad coding practice.  However I did find a different and surprisingly simple solution.

Rather than setting the window as minimised in the load method just set the WindowState property of the form to “Minimized”.  The load method then simply becomes…

Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles      
    MyBase.Load
    notifyiconMain.Visible = True
    Me.Visible = False
End Sub
Author: Stephen Millard
Tags: | vb |

Buy me a coffeeBuy me a coffee



Related posts that you may also like to read