How to handle close event of PowerShell window if user clicks on Close('X') button

后端 未结 3 776
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 11:25

I want to run some code before PowerShell 2.0 window is closed. For this I tried:

PS > register-engineevent PowerShell.Exiting -action {get-process | out-file c:

3条回答
  •  心在旅途
    2020-12-06 11:54

    The unhandled exception occurs because garbage collection has already disposed your handler by the time the unmanaged method is called. You can get around that by storing it in a static field:

    private static HandlerRoutine s_rou;
    
    public static void SetHandler()
    {
        if (s_rou == null)
        {
            s_rou = new HandlerRoutine(ConsoleCtrlCheck);
            SetConsoleCtrlHandler(s_rou, true);
        }
    }
    

提交回复
热议问题