The message loop and Application.Run
A console program ends when its Main returns. A WinForms program does not: it returns from Main only when the last window has closed. Between those two points sits one loop that reads the messages Windows has queued for the thread and sends each one to the control it belongs to. Understanding that loop is what separates a program that freezes from one that does not.
One loop, one thread
A WinForms application owns one thread, the user-interface thread. Every control was created on it, every control's state belongs to it, and the loop runs on it. When a button is pressed, Windows puts a WM_LBUTTONDOWN message in the queue of the thread; the loop takes it out, finds the button under the pointer and calls the button's window procedure; the button reacts by raising the .NET event Click, and your handler runs on the same thread, inside the same call.
That is why a handler that sleeps blocks the window: while the handler runs, nothing reads the queue, so no other message is processed, and the window does not repaint. The rule that follows is the subject of the thread part of the course: a long job goes to another thread, and the result comes back through Control.Invoke or IProgress<T>.
What Run does
using System;
using System.Windows.Forms;
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
var form = new Form1();
form.FormClosed += (sender, e) => Console.WriteLine("the last form closed");
Application.Run(form);
Console.WriteLine("Main continues");
}
}
internal sealed class Form1 : Form
{
public Form1()
{
Text = "The loop";
var close = new Button { Text = "Close", Dock = DockStyle.Top };
close.Click += (sender, e) => Close();
Controls.Add(close);
}
}
dotnet build app.csproj
Build succeeded.
0 Warning(s)
0 Error(s)
The listing is built and not run: once Application.Run starts, the program waits for a user, and there is no user here. What the two Console.WriteLine calls would print is documented, not observed: the first line when the form closes, the second when Run returns. With OutputType Exe those lines would go to a console window beside the form; with WinExe, which is what the project sets, they have nowhere to go, and a desktop program writes to a log file or a Debug listener instead.
Three forms of the call exist:
- Application.Run(form): shows the form and ends the loop when that form closes.
- Application.Run(): starts the loop with no form at all, and the program ends at the first Application.Exit() or ExitThread(). Useful for a tray application whose only window is a NotifyIcon.
- Application.Run(new ApplicationContext(form)): the loop ends when the context says so, which is how an application shows a login form and then a main window without ending in between.
Ending the loop
The loop ends in four ways, and the difference matters because each one skips a different amount of the shutdown:
- The last form closes: Application.Run(form) returns after FormClosed.
- Application.Exit(): asks every open form to close, raises FormClosing on each, and returns from the loop. A handler that sets e.Cancel = true keeps the application open.
- Application.ExitThread(): ends the loop of the current thread at once, without closing the forms. A thread that is not the user-interface thread needs form.BeginInvoke to call Application.Exit.
- Environment.Exit(code): ends the process immediately, runs no FormClosing and no finally. The exit code of the process is code.
A program that has to save unsaved work when the user closes the window uses FormClosing, which is the last moment at which the close can still be cancelled:
using System;
using System.ComponentModel;
using System.Windows.Forms;
internal sealed class Form1 : Form
{
private bool _dirty;
public Form1()
{
Text = "Unsaved work";
var box = new TextBox { Multiline = true, Dock = DockStyle.Fill };
box.TextChanged += (sender, e) => _dirty = true;
Controls.Add(box);
FormClosing += AskToSave;
}
private void AskToSave(object? sender, FormClosingEventArgs e)
{
if (!_dirty)
{
return;
}
var answer = MessageBox.Show(
"Discard the changes?",
"Unsaved work",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (answer != DialogResult.Yes)
{
e.Cancel = true;
}
}
}
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
This second listing is a fragment of a program on purpose: it is a form with no Main of its own, so the checker counts it and does not build it. The two listings together are what a form file and a program file look like, and lesson 006 puts such a pair side by side.
An ApplicationContext
An application that starts with a splash screen or a login form does not want the loop to end when that first form closes. ApplicationContext gives the loop another rule for when it ends:
using System;
using System.Windows.Forms;
internal sealed class NotesContext : ApplicationContext
{
public NotesContext()
{
var login = new Form { Text = "Sign in" };
var main = new Form { Text = "Notes" };
login.FormClosed += (sender, e) =>
{
if (MainForm == login)
{
MainForm = main;
main.Show();
}
};
MainForm = login;
login.Show();
}
}
internal static class Program
{
[STAThread]
private static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new NotesContext());
}
}
The loop watches MainForm: when the form that property names closes, Application.Run returns. Handing it another form keeps the application alive. Everything else about the loop is unchanged, including the rule that no handler may block for long.
Exercises
- Add a second form shown with Show and explain which of the two Application.Run(form) returns after.
- Replace Application.Exit with Environment.Exit(2) in a handler and say which events no longer run.
- Give the context a second form and decide when the application should end, then write the condition in words.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
When does Application.Run(form) return?
Answer
After the form closes
Run blocks on the message loop and returns when the form that owns it has closed.
-
On which thread does a Click handler run?
Answer
The user-interface thread, inside the message loop
The loop dispatches the message and the control raises the event on the same thread.
-
Why does a long loop in a Click handler freeze the window?
Answer
Nothing reads the message queue while the handler runs
Repainting and input are messages too, and they wait in the queue until the handler returns.
-
What does Application.Exit() do?
Answer
Asks every open form to close and returns from the loop
FormClosing runs for each form, and a handler that sets e.Cancel keeps the application open.
-
Which call ends the process without running FormClosing?
Answer
Environment.Exit
Environment.Exit ends the process immediately; the closing events are skipped.
-
What is e.Cancel for in a FormClosing handler?
Answer
Keeping the form open and stopping the close
The close is cancelled, which is how an unsaved-work prompt keeps the window alive.
-
Which class decides when Application.Run() ends when it is given one?
Answer
ApplicationContext, through its MainForm
The loop watches the MainForm of the context, so the application can outlive its first form.
-
A tray application has no visible form. Which call starts its loop?
Answer
Application.Run() with no arguments
The loop runs with no form and ends at Application.Exit or ExitThread.
-
What does Application.DoEvents() do to a handler that uses it to keep the window alive?
Answer
It processes queued messages from inside the handler, and re-enters your code
DoEvents re-enters the loop, so a click can run another handler while the first one is still on the stack.
-
Why does Main not return while the window is open?
Answer
Application.Run blocks on the message loop
Run is an ordinary blocking call: the loop is inside it, so Main waits there.
Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows.
Article author: Arthur Isaev