c# – What kind of windows applications can receive system events? – Education Career Blog

What kind of windows applications can receive system events?
I mean events like closed by user.
Windows forms, WPF applications and Windows services can do that. But I am not aware of any others.


Graphical applications based on Windows Forms and WPF listen to some Windows API events natively. Command-line and other types can subscribe to those events, but you have to write that code.


Here is an article on receiving Win32 API events from a managed application:


Note that your application must be running to receive the events, so if you want to do this from a console application your app would have to start and remain running until some external signal causes it to close.


Getting events like this requires a window and a message loop. The window is taken care of by SystemEvents, the message loop is automatically there in a WPF or winforms app.

It is smart enough to create a dedicated thread if you use it in another type of app, like a service or a console mode app. You’ll see that thread back in the debugger (Debug + Windows + Threads) with the name “.NET SystemEvents”. This will happen when your app runs in a non-interactive Windows workstation (like services) or when your Main method doesn’t have the STAThread attribute (like console apps).

Nothing special is needed in your code to subscribe the event. But do beware that your event handler will run on this helper thread, synchronization with the lock keyword might be necessary.

Leave a Comment