Reputation: 45771
I am confused about how to make a Form visible. When we create a Windows Forms application, the default Form1 is automatically visible, even without explicit call to Show method. But if we want to show another Form and make it visible, we have to make it visible by calling Show.
Any ideas why there is such differences?
I am using VSTS 2008 + C# + .Net 2.0.
Upvotes: 1
Views: 1380
Reputation: 158309
This is because Form1 will be the main form of the application. Specifically, it will be passed to the Application.Run
method, which will create an ApplicationContext
object with Form1 assigned as main form. When the application starts, it checks if the ApplicationContext
has a main form and if so, the Visible
property of that form will be set to true
, which will cause the form to be displayed.
Or, expressed in code, this is Application.Run
:
public static void Run(Form mainForm)
{
ThreadContext.FromCurrent().RunMessageLoop(-1, new ApplicationContext(mainForm));
}
RunMessageLoop
will call another internal function to set up the message loop, and in that function we find the following:
if (this.applicationContext.MainForm != null)
{
this.applicationContext.MainForm.Visible = true;
}
This is what makes Form1 show.
This also gives a hint on how to act to prevent Form1 form showing automatically at startup. All we need to do is to find a way to start the application without having Form1 assigned as main form in the ApplicationContext
:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// create the form, but don't show it
Form1 form = new Form1();
// create an application context, without a main form
ApplicationContext context = new ApplicationContext();
// run the application
Application.Run(context);
}
Upvotes: 2
Reputation: 7238
because form1 is the main form that is called by Application.Run(new form1());
you'll find this code in the program.cs file and you can change to be any form.
Upvotes: 1
Reputation: 26468
Take a look at the file "Program.cs" that VS generates for you.
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()); // and especially this line :)
}
}
Upvotes: 4