C#关闭Process并运行Code on Process

时间:2018-04-06 14:40:30

标签: c# process exit

我想在Application Exit上运行代码。我的问题是我有两个应用程序。第一个正在运行。我的第二个应用程序现在将关闭第一个应用程序。但是在关闭时我想在第一个应用程序中运行代码。

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();
    }   
}

1 个答案:

答案 0 :(得分:1)

试试这个......

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;
        }
    }