3

I've read dozens of existing questions on here, they all come up with the same solutions, unfortunately none of these work. It seems they only work when the X button is clicked on a console application.

I am asking, is there a way to run some code when the console is forced closed? This means force closing the task in task manager, or the operating system froce closing it for any reason.

I've tried pretty much every existing solution on open questions of this site. This is not a duplicate. I repeat, this is not a duplicate. It's simply asking for something totally different.

Have I tried anything so far? No, I've tried all the usual, assigning a callback function to all kinds of events, but nothing actually works. I've done this before in a WinForm, but can't in console.

fskdjwe
  • 157
  • 8
  • 2
    I think its not directly possible but maybe you can have a separate background app **B** that monitors your app **A** and if **A** is force closed then app **B** calls your method. but if background app i.e **B** also gets force closed you can re-spawn that from **A**. – M.kazem Akhgary Aug 11 '18 at 10:43
  • How is B going to know if A was force closed, and not just soft closed using the X? I also don't like A having to depend on another application B. – fskdjwe Aug 11 '18 at 10:45
  • 2
    Possible duplicate of [What's the best way to watchdog a desktop application?](https://stackoverflow.com/questions/11146381/whats-the-best-way-to-watchdog-a-desktop-application) – Rui Jarimba Aug 11 '18 at 10:47
  • @fskdjwe i have not done that myself but i had experience when i wanted to force close an app it would recover itself. there has to be another app or service that does this so they can protect each other. – M.kazem Akhgary Aug 11 '18 at 10:52
  • You can create an event using the handle. See Pinvoke : http://www.pinvoke.net/default.aspx/kernel32/CreateEvent.html – jdweng Aug 11 '18 at 10:54

1 Answers1

0

You may be looking for Application Recovery & Restart. The Application Recovery and Restart (ARR) technologies enable developers to customize an application's behavior when WER terminates the application due to an unrecoverable error.

Refer: https://msdn.microsoft.com/en-us/library/cc303699.aspx

-- Or for a more general and reliable fix --

First application can start a second application (if not already running in background). You can use this second application (running as a background service) to "watch" the first application which can start it again on close. You can modify the behavior based on clean exit of first application as well. Very simple approach to start the process would be:

    // Wait for the process to terminate
    Process process = null;
    try
    {
        process = Process.GetProcessById(pid);
        process.WaitForExit(1000);
    }
    catch (Exception ex)
    {
        // Handle appropriately
    }
    Process.Start(applicationName, "");
RKalra
  • 531
  • 7
  • 10