C#: Don’t display the startup form.
Something that often seems to be a problem with beginning C# developers is the display of the initial form. Normally one would always want the startup form to be displayed as soon as possible–but sometimes the application lives in the tray, or should not initially display a window.
One may first think that an event in System.Windows.Forms.Form can be handled, and the form may be directed to Hide. Unfortunately, this won’t work as expected, the Form will always get the SW_SHOW message when Application.Run() is executed.
When creating a new project, Visual Studio will generate a Program.cs which looks similar to the following:
namespace CamOn { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
When Application.Run is invoked with a Form parameter, it will create and show the window. The easiest way to override this behavior is to simply not call Application.Run with the form:
namespace CamOn { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); new Form1(); Application.Run(); } } }
Form1 will still be created and pump messages – but it won’t initially be shown.
