tags:

views:

39

answers:

2

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.

+2  A: 

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.

UPDATE:

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

http://www.codeproject.com/KB/cs/interopevents.aspx

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.

Dave Swersky
Would you please guide me to a tutorial or something on how can it be done with console applications? Thank-you very much!
Kaveh Shahbazian
+1 for doing the OP's research for him.
Wonko the Sane
@Wonko_the_Sane So what kind of questions I should ask here? You'r so sure of judging people as you do! You are a great developer! Congratulation!
Kaveh Shahbazian
@Dave_Swersky since I needed on start and on exit events, I have found another way to do that. For on start, I just execute code I need for that and then System.Windows.Forms.Application.ApplicationExit.AddHandler(fun s e -> what_ever_on_end );; Application.Run() and that worked! Thanks again!
Kaveh Shahbazian
+1  A: 

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.

Hans Passant