0

我正在用 C# 构建一个窗口应用程序,它会在任何切换用户发生时通知我。现在 m 使用“SessionSwitch”事件来获取通知。

private void startLisning()
{
        Microsoft.Win32.SystemEvents.SessionSwitch +=new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
        this.eventHandlerCreated = true;
}

private void SystemEvents_SessionSwitch(object sender, EventArgs e)
{
        System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "SwitchUser\t" + DateTime.Now.ToString() + Environment.NewLine);


}

但在这种情况下,它也会在“解锁”发生时发送通知。这是我不想要的。我只需要当任何用户在他的系统中切换用户时,我的应用程序应该收到通知并将其记录到日志文件中。它应该只在 lock 或 switchUser 发生时记录。

提前致谢。

4

1 回答 1

0
   private void Form1_Load(object sender, EventArgs e)
    {
        startLisning();
    }
    private bool eventHandlerCreated;

    private void startLisning()
    {
        Microsoft.Win32.SystemEvents.SessionSwitch +=new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
        SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch1);

        this.eventHandlerCreated = true;
    }


    private void SystemEvents_SessionSwitch1(object sender, SessionSwitchEventArgs e)
    {
        switch (e.Reason)
        {
            case SessionSwitchReason.SessionLock:
                System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "LOCK\t" + DateTime.Now.ToString() + Environment.NewLine);
                break;
            case SessionSwitchReason.SessionLogon:
                System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "LOGIN\t" + DateTime.Now.ToString() + Environment.NewLine);
                break;
            case SessionSwitchReason.SessionUnlock:
                System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "UNLOCK\t" + DateTime.Now.ToString() + Environment.NewLine);
                break;
            case SessionSwitchReason.ConsoleConnect:
                System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "UnlockAfetSwitchUser\t" + DateTime.Now.ToString() + Environment.NewLine);
                break;
            case SessionSwitchReason.ConsoleDisconnect:
                System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "SwitchUser\t" + DateTime.Now.ToString() + Environment.NewLine);

                break;
        }

    }

这将在“切换用户”发生时通知,并在“用户恢复”时通知。'SessionSwitchReason.ConsoleDisconnect' 是任何切换用户发生时触发的事件。此代码已在 windows7 中测试,并且运行良好。

此代码在 Appdata 文件夹中创建一个“testtest.txt”日志文件。你可以通过使用 Window+r 并搜索 '%appdata%' 到达那里。

它记录通知如下: 1. 使用日期时间登录 2. 使用日期时间锁定 3. 使用日期时间解锁 4. 使用日期时间切换用户 5. 使用日期时间切换用户恢复

于 2015-04-15T16:29:36.077 回答