1

I'd like to Run Code on Application Exit. My Problem is that I have two Application. The First is running. My Second Application now is going to Close the First Application. But on Closing I'd like to run code in the First Application.

public class First
{
   public static Main(string[] args)
   {
        Console.ReadLine();
   }

  public void DoSomethingOnExit()
  {
    Console.WriteLine("It Works");
    Thread.Sleep(1000);
  }
}


public class Second
{
    public void method(int number)
    {
        var prozess = Process.GetProcessById(number);
        prozess.Close();
    }   
}
maccettura
  • 10,514
  • 3
  • 28
  • 35
Homer Tw
  • 85
  • 9
  • You could use a named-pipe or some other kind of inter-process communication. – Ron Beyer Apr 06 '18 at 14:43
  • Is it a console app? If so then it's a duplicate of [.NET Console Application Exit Event](https://stackoverflow.com/questions/1119841/net-console-application-exit-event) – stuartd Apr 06 '18 at 14:44
  • 1
    This should be split into 2 questions, One about executing a method on application exit and one on communication between 2 apps. One showing lack of research and the other about using SO as code service. – Franck Apr 06 '18 at 14:47

1 Answers1

1

Try this...

static void Main(string[] args)
    {
        _handler += new EventHandler(Handler);
        SetConsoleCtrlHandler(_handler, true);

        Console.WriteLine("Running");            
        Console.ReadLine();            
    }



 [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);

    private delegate bool EventHandler(CtrlType sig);
    static EventHandler _handler;

    enum CtrlType
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT = 1,
        CTRL_CLOSE_EVENT = 2,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT = 6
    }

    private static bool Handler(CtrlType sig)
    {
        switch (sig)
        {
            case CtrlType.CTRL_C_EVENT:
            case CtrlType.CTRL_LOGOFF_EVENT:
            case CtrlType.CTRL_SHUTDOWN_EVENT:
            case CtrlType.CTRL_CLOSE_EVENT:
                DoSomeShutdownStuff();
                return true;

            default:
                return false;
        }
    }
Thomas
  • 216
  • 3
  • 8