Detect Close via X button in Console App

Good day,

We have a VS2005 C# Console Application and are trying to detect the user closing by hitting the X button in the top right corner of the app. As you can see by the following code, we have tried hooking up a variety of event handlers, but in all cases the event handler never gets called. What are we missing

Thanks in advance...

static void Main(string[] args)

{

// get notification of close

AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);

//Application.ThreadExit += new EventHandler(Application_ThreadExit);

//Application.ApplicationExit += new EventHandler(Application_ApplicationExit);

//Process.GetCurrentProcess().EnableRaisingEvents = true;

//Process.GetCurrentProcess().Exited += new EventHandler(CurrentProcessExited);

// keep console alive until user hits X button

while (true)

{

}

}

static void CurrentDomain_ProcessExit(object sender, EventArgs e)

{

// cleanup/shutdown

int i = 0;

i++;

}



Answer this question

Detect Close via X button in Console App

  • soni_ace

    Given that this is a console app that is likely not using the windows messaging pump you may want to look into using SetConsoleCtrlHandler.

  • pgw1959

    Thanks for the feedback Brendan.

    I had found the same article and based my attempt to use Process.Exited on it. A couple of questions:

    Is there a managed .NET way to do this without dll import

    How does one turn on the Windows message pump for a console app and what are the implications

    Thanks again...


  • RogerRV

    Randal Greene wrote:
    How does one turn on the Windows message pump for a console app and what are the implications


    Add Application.Run() to your console application, which is really the main difference between a console app and a winform. Note there are threading issues to deal with...check out a similar question I had and the response concerning Application Run.


  • Detect Close via X button in Console App