0

我需要监控一些系统事件,如关机、注销、锁定等。

现在我有两个问题:

  1. 在系统关闭、注销或类似情况之前,我该如何做某事?
  2. 当进程被任务管理器杀死时,我是否有机会在它关闭之前做某事,而无需第二个进程?应该不会吧?(没那么重要)

到目前为止我所拥有的:

    public MainWindow()
    {
        InitializeComponent();
        SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
        SystemEvents.SessionEnded += SystemEvents_SessionEnded;
        SystemEvents.EventsThreadShutdown += SystemEvents_ThreadShutdown;
        SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
    }

    private void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
    {
        if(e.Mode == PowerModes.Suspend)
        {
            Thread.Sleep(5000);
            Log("PowerMode Suspend: " + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
        }
        else if(e.Mode == PowerModes.Resume)
        {
            Thread.Sleep(5000);
            Log("PowerMode Resume: " + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
        }
    }

    private void SystemEvents_ThreadShutdown(object sender, EventArgs e)
    {
        Thread.Sleep(5000);
        Log("EventThread Shutdown: " + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
    }

    private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
    {
        if (e.Reason == SessionSwitchReason.SessionLock)
        {
            Thread.Sleep(5000);
            Log("Locked the machine: " + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
        }
        else if (e.Reason == SessionSwitchReason.SessionUnlock)
        {
            Thread.Sleep(5000);
            Log("Unlocked the machine: " + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
        }
        else if (e.Reason == SessionSwitchReason.SessionLogoff)
        {
            Thread.Sleep(5000);
            Log("Logged of the machine: " + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
        }
    }

    private void SystemEvents_SessionEnded(object sender, SessionEndedEventArgs e)
    {
        if (e.Reason == SessionEndReasons.SystemShutdown)
        {
            Thread.Sleep(5000);
            Log("Shutdown of the machine: " + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
        }
        else if (e.Reason == SessionEndReasons.Logoff)
        {
            Thread.Sleep(5000);
            Log("Logoff of the machine: " + DateTime.Now.ToString("HH:mm:ss") + "\r\n");
        }
    }

睡眠应该模拟此事件之前的一些待办事项。只有 Windows Lock & Window Closed 起作用,其他的不起作用,可能是因为程序已经关闭。

知道我该如何解决吗?

4

0 回答 0