C#: Hide Main Form
It’s always been a pain in the neck just to hide the main form in a Windows Form application in C#. There are several ways to do it. By setting the Visible property to false, and using this.Hide(). Bad news is, the two ways I mentioned doesn’t work. Good news is, I got two solutions for this.
The Problem: Why it won’t work?
It’s very hard to brainstorm, explore, and get into trial just to hide the main form. It takes a lot of time and effort. But why does these two, supposed to be working solutions, don’t work? The answer is pretty much complicated, as I am not sure about my answer as well. If you look at your code, there’s definitely nothing wrong with it. The reason why it keeps on showing up, even if we put the right values into these properties, is because the form we are trying to hide is the main form, and it won’t allow us to hide Application.Run(new Form1()) overrides those properties.
The Solutions
I have two solutions for this, one is not so good and the other one seems to be the best. The first solution, is to change the Opacity value of the form from 100 to 0.
this.Opacity = 0;
Or you can just set it at the Properties window in your form designer. Actually, the above solution only works on Windows Operating Systems with Aero enabled (Please correct me if I am wrong here). So if you are using XP or editions of Vista and 7, this won’t work.
The second one, is by modifying Program.cs, the main source file of your C# project. In this solution, the form application will be defined, but it won’t be loaded. And of course, the program stays up and running.
//Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace FileIndex
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 mForm = new Form1();
//Your On Load code here..
Application.Run();
}
}
}
Originally, the Application.Run(); function calls the main form. But in this solution, it doesn’t have to. This will load your application, but will not load the form. The only thing you can’t do here is, place your code at the OnLoad event of the form, since the form will not load. Alternatively, you can place your code between the Form definition, and Application.Run();.
But why declare and define Form1 if we won’t load it? It won’t load, but it doesn’t mean its not functional. You can still use components on that form, like Timer, NotifyIcon, etc. You can also put your stealthy functions in your Form code if you wish.
Dealing with these kind of problems isn’t hard. You just need to think critically, and trace where the problem is coming from.
Pingback: C#: Hide Main Form | Lifecode | Learn Visual Studio