• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 289
  • Last Modified:

Detecting Console Application Closing...

In C#, I'm trying to figure out a way to perform an action (some piece of code) when the user closes a console application (note: NOT a GUI application), i.e. when the "X" on the console window is clicked to close the window.  Is this possible?  Thanks!
0
DiamonDogX
Asked:
DiamonDogX
  • 3
  • 2
1 Solution
 
aprestoCommented:
Dont think it is, i will confirm but i doubt it
0
 
aprestoCommented:
Had a look, can't find anything.

the closest i came was using a destructor but that only fired when the console app terminates properly:

~Your_Class_Name()
{
         Console.WriteLine("Shutting down, please wait...");
         Console.ReadLine();
}

0
 
vo1dCommented:
you can use the processexit event of the current appdoamin to check, if your console app is going to shutdown.

AppDomain appDomain = AppDomain.CurrentDomain;
appDomain.ProcessExit += new EventHandler(appDomain_ProcessExit);

but this wil not safe your app to be closed via the 'x' button or windows message.
for this, i would recommend a windows hook to prevent, that the WM_CLOSE message will be send to the console window, where your app is running.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
vo1dCommented:
here is an example, how a windows hook works.
http://www.codeproject.com/csharp/NetWin32Hooks.asp
0
 
DiamonDogXAuthor Commented:
vo1d,
That link has code that appears to only work for System.Windows.Forms applications.  Still having problems determining when that console window is being closed... tried various C# functions such as the AppDomain one you described above.  Doesn't seem to be possible unless you have some other program/process monitoring your other one...
0
 
vo1dCommented:
the example is for a windows form, but if you use the win32 api functions via pinvoke you can use it in your application.
you will have to use the findwindow function to get a handle to your console window and then you could trap the wm_close message for that window.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now