What isn't available to me before calling Application.Run() in a standard WinForms application?
I want to do some initialization of开发者_JAVA百科 various things at runtime of my WinForms application. I'm looking specifically at the Program.cs
file that every WinForm application has. In it, I see:
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
I know that this is what starts up the application and creates the initial form (in my case, an instance of frmMain
).
Can I not just put my initialization code before Application.Run()
? The initialization I need to do is to check a few registry entries, create them if necessary, and connect to a database. Will any feature not be available to my instantiation code if I put it before Application.Run()
?
Application.Run()
starts message loop for your main thread. SO before that line of code you can do anything except what is dependent on windows messages (click, keyup, ...)
A Windows Forms application starts when the Main
method is called. You can implement initialization procedures on the Main
function. However, to initialize a Windows Forms application fully and start it routing Windows Forms events, you need to invoke Application.Run
.
Read about Application
Yes, no problem, the code in Main() is boilerplate but not cast in stone.
Do keep in mind that any code you run before calling Application.Run() will delay the startup of your user interface. Once that goes over a second or two, give or take, you might want to consider displaying a splash screen so that the user gets some visual feedback that your program got started. Well supported by the .NET framework, check this answer.
One important thing you don't have available before Run
is a valid SynchronizationContext.Current
. So if you use any kind of event-based asynchronous pattern components, they'll seem to work just fine, but will fire their events on a thread pool thread instead of the GUI thread.
Because of this, any asynchronous startup code that queues completion events to the GUI should be started from an event, not before Run
.
As long as you don't need to access anything declared in frmMain
you should be OK.
However the MSDN states:
Begins running a standard application message loop on the current thread.
so you won't have access to the message loop.
There is another overload Application.Run(ApplicationContext)
that will let you execute code before your form is displayed - this appears to be the way to go.
The example code on this page does some initialisation before showing two forms, so you should be OK with your model.
精彩评论