系统事件记录

时间:2012-10-15 11:07:43

标签: c# events system

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

现在我有两个问题:

  1. 如何在系统关闭,注销或类似之前执行某些操作?
  2. 当进程被taskmanager杀死时,我有没有机会在它关闭之前做一些事情而没有第二个进程?可能不是或? (不是那么重要)
  3. 到目前为止我所拥有的:

        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确实有效,其他没有,可能是因为该程序已经关闭。

    我知道如何解决这个问题吗?

0 个答案:

没有答案