473,223 Members | 1,790 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,223 software developers and data experts.

killing a process from task manager does not fire console CTRL_CLOSE_EVENT

Hi,
I need to do some important cleanup before my console application
exists. I used the console ctrl event. This is working well and it
fires for all cases, including the CTRL_CLOSE_EVENT (if I close the
application from the X botton). But on
the contrary to what the MSDN indicates
(ms-help://MS.VSCC.2003/MS.MSDNQTR.2003OCT.1033/dllproc/base/handlerroutine.htm),
ending my process from the task manager did not fire the
CTRL_CLOSE_EVENT.
I also tried to use the Appdomain processexit, which didn't work for
any of the cases.
This is the code as I tried it:
public enum ConsoleEvent
{
CTRL_C = 0,
CTRL_BREAK,
CTRL_CLOSE,
CTRL_LOGOFF = 5,
CTRL_SHUTDOWN
}
public delegate void ControlEventHandler(ConsoleEvent
consoleEvent);
public event ControlEventHandler ControlEvent;
ControlEventHandler eventHandler;
public ConsoleCtrlEventsSetup()
{
// save this to a private var so the GC doesn't
collect it...
eventHandler = new
ControlEventHandler(Handler);
SetConsoleCtrlHandler(eventHandler, true);
}
~ConsoleCtrlEventsSetup()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
}
if (eventHandler != null)
{
SetConsoleCtrlHandler(eventHandler,
false);
eventHandler = null;
}
}
private void Handler(ConsoleEvent consoleEvent)
{
if (ControlEvent != null)
ControlEvent(consoleEvent);
}
[DllImport("kernel32.dll")]
static extern bool
SetConsoleCtrlHandler(ControlEventHandler e, bool
add);
}
class CrashHandler
{
public static void
MyProcessExitHandler(ConsoleCtrlEventsSetup.Consol eEvent consoleEvent)
{
StopAllMotions();
}
public static void StopAllMotions ()
{
StreamWriter y =
File.AppendText(@"c:\temp\test.txt");
y.WriteLine("stopping all motions");
y.Flush();
y.Close();
}
}
public static void Main()
{
ConsoleCtrlEventsSetup cc = new
ConsoleCtrlEventsSetup();
cc.ControlEvent += new
ConsoleCtrlEventsSetup.ControlEventHandler(MyProce ssExitHandler);
Console.WriteLine("Press any key to exit");
}
Any ideas?
Thanks.

Dec 21 '05 #1
10 8383
shiry,

Task Manager provides two ways of ending a process - from the *Applications*
tab clicking on the *End Task* button and from the *Processes* tab clicking
on the *End Process* button.

The *End Task* button is the one that MSDN referes to. The ctrl event should
fire in this case.

I doubt it that you'll get the event if one clicks on the *End Process*
button, though. It even warns you when you do that.
Ending a process with this button is abnormal termination.
--

Stoitcho Goutsev (100) [C# MVP]

"shiry" <sh****@gmail.com> wrote in message
news:11*********************@f14g2000cwb.googlegro ups.com...
Hi,
I need to do some important cleanup before my console application
exists. I used the console ctrl event. This is working well and it
fires for all cases, including the CTRL_CLOSE_EVENT (if I close the
application from the X botton). But on
the contrary to what the MSDN indicates
(ms-help://MS.VSCC.2003/MS.MSDNQTR.2003OCT.1033/dllproc/base/handlerroutine.htm),
ending my process from the task manager did not fire the
CTRL_CLOSE_EVENT.
I also tried to use the Appdomain processexit, which didn't work for
any of the cases.
This is the code as I tried it:
public enum ConsoleEvent
{
CTRL_C = 0,
CTRL_BREAK,
CTRL_CLOSE,
CTRL_LOGOFF = 5,
CTRL_SHUTDOWN
}
public delegate void ControlEventHandler(ConsoleEvent
consoleEvent);
public event ControlEventHandler ControlEvent;
ControlEventHandler eventHandler;
public ConsoleCtrlEventsSetup()
{
// save this to a private var so the GC doesn't
collect it...
eventHandler = new
ControlEventHandler(Handler);
SetConsoleCtrlHandler(eventHandler, true);
}
~ConsoleCtrlEventsSetup()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
}
if (eventHandler != null)
{
SetConsoleCtrlHandler(eventHandler,
false);
eventHandler = null;
}
}
private void Handler(ConsoleEvent consoleEvent)
{
if (ControlEvent != null)
ControlEvent(consoleEvent);
}
[DllImport("kernel32.dll")]
static extern bool
SetConsoleCtrlHandler(ControlEventHandler e, bool
add);
}
class CrashHandler
{
public static void
MyProcessExitHandler(ConsoleCtrlEventsSetup.Consol eEvent consoleEvent)
{
StopAllMotions();
}
public static void StopAllMotions ()
{
StreamWriter y =
File.AppendText(@"c:\temp\test.txt");
y.WriteLine("stopping all motions");
y.Flush();
y.Close();
}
}
public static void Main()
{
ConsoleCtrlEventsSetup cc = new
ConsoleCtrlEventsSetup();
cc.ControlEvent += new
ConsoleCtrlEventsSetup.ControlEventHandler(MyProce ssExitHandler);
Console.WriteLine("Press any key to exit");
}
Any ideas?
Thanks.

Dec 21 '05 #2
Thanks,
So, that means that I cannot catch an Application crash in this manner?
What about AppDomain.CurrentDomain.ProcessExit function, can it help me
in case of a crash?
I read somewhere that the only way to catch a crash, in order to do
some cleanup, is to run a watcher application that uses the
System.Diagnostics.Process class, and get the return code of the
application. Is that correct? Is there any other way of doing this?

Dec 22 '05 #3

"shiry" <sh****@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Thanks,
So, that means that I cannot catch an Application crash in this manner?
What about AppDomain.CurrentDomain.ProcessExit function, can it help me
in case of a crash?
I read somewhere that the only way to catch a crash, in order to do
some cleanup, is to run a watcher application that uses the
System.Diagnostics.Process class, and get the return code of the
application. Is that correct? Is there any other way of doing this?


Killing a process is not an application crash isn't it?
When killing a process (from process explorer or whatever), the OS removes
the process cold, nothing is signaled because you are not supposed to kill a
process, unless it is no longer "functional", that is, it's no longer
runnable/responding, and because of this the OS sees no reason to signal the
process that it's going to be killed.
If you need to handle application crashes, you'll have to install a catch
handler.
Willy.
Dec 22 '05 #4
What do you mean by: "install a catch handler"?
(I'm pretty new to all this programming business, so excuse me for my
novice questions)

Dec 22 '05 #5
If you just need to do some cleanup, you can tie into the Process
Exited event. To do this you would have to have a watcher function like
you mentioned. All you would have to do is find your applications
Process object and use the following code.

Process currentProc = <your process, many ways to get this>;
currentProc.Exited += new EventHandler(processExited);

void processExited(object sender, EventArgs e)
{
//your clean up code goes here
}

Hope this helps

Dec 22 '05 #6
Just make sure you set process.EnableRaisingEvents to *true* otherwise the
exit event won't fire.
--

Stoitcho Goutsev (100) [C# MVP]

"Justin Creasy" <ju***********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
If you just need to do some cleanup, you can tie into the Process
Exited event. To do this you would have to have a watcher function like
you mentioned. All you would have to do is find your applications
Process object and use the following code.

Process currentProc = <your process, many ways to get this>;
currentProc.Exited += new EventHandler(processExited);

void processExited(object sender, EventArgs e)
{
//your clean up code goes here
}

Hope this helps

Dec 22 '05 #7
Good call Stoitcho, I can't believe I forgot to mention that seeing as
I spent probably around 2 hours trying to find out why my event wasn't
firing and that was the answer. Thanks for catching that!

Dec 22 '05 #8

"Justin Creasy" <ju***********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
If you just need to do some cleanup, you can tie into the Process
Exited event. To do this you would have to have a watcher function like
you mentioned. All you would have to do is find your applications
Process object and use the following code.

Process currentProc = <your process, many ways to get this>;
currentProc.Exited += new EventHandler(processExited);

void processExited(object sender, EventArgs e)
{
//your clean up code goes here
}

Hope this helps


This doesn't work for our own process (CurrentProcess), it only works for
process spawned from this process.
So there is nothing you can do in your handler other than accessing some of
the process properties like ExitCode, ExitTime ....
The reason for this is that the event is raised by the OS to the parent of
the process after the process has terminated.

Willy.
Dec 22 '05 #9

"shiry" <sh****@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
What do you mean by: "install a catch handler"?
(I'm pretty new to all this programming business, so excuse me for my
novice questions)


Something like this for a console program, will catch unhandled
exceptions...

public static void DoSomethingNasty()
{
int x=0,y=1;
Console.Write((y/x).ToString()); // this will throw a "devide by zero"
exception
}
static void Main(string[] args)
{

AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(GenericErrorHandler );
// Start a thread and do something bad...
Thread t = new Thread(new ThreadStart(DoSomethingNasty));
t.Start();
t.Join();
}
static void GenericErrorHandler(object sender,UnhandledExceptionEventArgs
e)
{
Console.WriteLine("Exiting...");
System.Environment.Exit(1); // terminate process and return error code
1 to parent process
}
Note that this doesn't catch process terminated by a "Kill" command!!!

Willy.
Dec 22 '05 #10
Thanks guys.
You've helped me a lot!

Dec 26 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: Michael Kearns | last post by:
I've been using python to write a simple 'launcher' for one of our Java applications for quite a while now. I recently updated it to use python 2.4, and all seemed well. Today, one of my...
77
by: Charles Law | last post by:
Hi guys I have a time critical process, running on a worker thread. By "time critical", I mean that certain parts of the process must be completed in a specific time frame. The time when the...
5
by: Paul Bergson | last post by:
I have been trying to get a process to start up and run with arguments passed to it. I have gotten close (Thanks to help from this board) but I there is a failure while I'm running this because...
5
by: Dougal Fair | last post by:
Hello, I have written a vb.net program that invokes an Access2000 report in Preview mode, so that it shows on the screen. My program then goes on its merry way and the user can read the report...
6
by: Alexander Widera | last post by:
hello, if i start a program (an exe-file) with Process.Start(...) I don't have the required permissions that the programm needs (i could start the programm but the program needs special rights)....
4
by: Strah | last post by:
Is there a way to catch the event of terminating the application from the the processes tab in task manager? I have created windows app, and if a user termintates the app in the task manager,...
2
by: tony.newsgrps | last post by:
Hi there, I'm trying to understand the impact of killing a process that owns a system mutex (used to ensure there is only 1 instance of my program running) Here is my code pretty much: try...
4
by: Miro | last post by:
I'm using VB.Net 2003 I have code - it works great - to kill a process(s) if they are running. ---- Dim myProcesses() As Process 'Funny - withouth the () in the myProcesses it does not work...
9
by: SeC | last post by:
Hi. Is there any way to detect if application is being killed by 'End Process' via Task Manager ?
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.