16

I am just starting .Net development (C#) and have come across some code that has me slightly confused....

If I have

Form myForm = new Form();

What does the following line actually do:

Application.Run(myForm);

Does it essentially do the same thing as myForm.ShowDialog() or myForm.Show() (that's what I thought, when running a form will do).....

I always find that the msdn is a poor resource for properly explaining material to new comers

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
user559142
  • 12,279
  • 49
  • 116
  • 179
  • See [this question](http://stackoverflow.com/questions/5200292/application-runform-vs-form-show) – nickd Jan 20 '12 at 12:42

2 Answers2

18

Application.Run(myForm); makes that form visible to user. It is the first form which get loaded in memory. And it runs this form in a message loop, so that you get all user events.

Short Answer:

Application.Run begins running a standard application message loop on the current thread.

Long Answer:

Application.Run causes the windows application enters the message loop within Winmain to process various windows messages the OS posts to a message queue.The message loop, "Loops" until its receives a WM_QUIT message. It uses GetMessage and PeekMessage to retrive messages and PostMessage to sent the retrived messages to Windows procedure.

If you do

Form myForm = new Form(); 
myForm.Show();

it will show the form and exit out. You will use new Form() & .Show() when you want to launch a new form from existing form.

Hope this answers your question.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
  • 4
    The important thing here is the message loop. WIthout this you basically open a windo without the messaging loop running. – TomTom Jan 20 '12 at 11:34
  • 2
    Indeed, it's the message pump. You would find it much easier to understand if you had done any C++ Windows development - the higher level of abstraction of C# makes some things harder to grasp. – Vladislav Zorov Jan 20 '12 at 11:39
  • @VladislavZorov that's right. I had done some stuff in VC++, even in that you get lots of stuff cooked. – Amar Palsapure Jan 20 '12 at 11:42
  • BTW, should we dispose `myForm` after `Application.Run(myForm)` line? as SolarLint suggests – Yousha Aleayoub Jun 01 '20 at 19:33
4

to start an application with a main form, so that the application terminates when the main form is closed. it will be associated to the current thread. it runs this form in a message loop.

Message Loop means : They act upon messages that the operating system posts to the main thread of the application. These messages are received from the message queue by the application by repeatedly calling the GetMessage (PeekMessage) function in a section of code called the "event loop."

Application Run()

Robinson
  • 23
  • 4
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83