Right now I am using Process.Kill() to kill a process. Is there a way though, instead of just killing it immediately, that I can like send a message to the process instructing it to close so that it can gracefully clean up and shut down. Basically, I'm looking for the equivlent to just clicking the red X in the upper right hand corner, which I believe DOES send a message to the application requesting a shut down.
Asked
Active
Viewed 1.8k times
27
-
This has been asked, and an answer has been accepted here: http://stackoverflow.com/questions/2055753/how-to-gracefully-terminate-a-process – David Aug 05 '10 at 05:33
-
@David Stratton Good find and yes the idea is the same, but this question is specifically asking about managed code (see tags [c#] and [.net]), which there is not yet an answer for on the other question – lc. Aug 05 '10 at 05:35
-
@David Stratton - This question is about graceful shutdown using managed code with C#, the link you put up is about win32 and the answers require pInvokes. Not the same at all. – Oded Aug 05 '10 at 05:37
-
@David Stratton Ic is right. I was looking for a managed C# way to do this. He answered my question perfectly. – Icemanind Aug 05 '10 at 05:37
-
Ah, sorry.. My thought process was... This will work from .Net code using PInvoke.., You can call any Win32 API function from .Net using PInvoke. However, I understand if you're looking for "Pure" managed code. – David Aug 05 '10 at 05:39
3 Answers
38
If the process has a windows interface (as you refer to the red "X"), you can try Process.CloseMainWindow(). If it fails, you can fallback to Process.Kill().
lc.
- 109,978
- 20
- 153
- 183
-
-
Is it possible to run something like this from shell? I have a very long process that i may need to shut down some of the way through. – SJ10 Jul 31 '18 at 18:48
5
Killing can not be graceful, perhaps you can signal the process to commit suicide. For signaling you have many options.
- SendMessage
- NamedPipes
- Named Mutex
- Sockets
Muhammad Hasan Khan
- 33,784
- 16
- 85
- 129
3
It would depend on the process you're killing. As stated at on the relevant page for Process.Kill, "Kill is the only way to terminate processes that do not have graphical interfaces." If there is a graphical window, then go with the answer by lc above; Process.CloseMainWindow functions as the red X you referred to.
JBirch
- 629
- 1
- 4
- 12