简体   繁体   English

使用 c# 检测注销时出现问题

[英]problem in detecting logoff using c#

I tried to detect logoff event and write it in a text.我试图检测注销事件并将其写入文本。

How can this be fixed?如何解决这个问题? i wanted to write the logoff time in a text file but the text file is not created when i logoff the PC.我想在文本文件中写入注销时间,但是当我注销 PC 时没有创建文本文件。

static void Main(string[] args)
{
    SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
    Console.ReadLine();
    SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
    if (e.Reason == SessionSwitchReason.SessionLogoff)
    {
        TextWriter tw = new StreamWriter("D:\\date.txt");
        tw.WriteLine("logoff" + DateTime.Now);
        tw.Close();
    }
    if (e.Reason == SessionSwitchReason.SessionLogon)
    {
        TextWriter tw1 = new StreamWriter("D:\\date.txt");
        tw1.WriteLine("logoff" + DateTime.Now);
        tw1.Close();
    }
}

This won't work unless the app has a facility for reading Windows messages which your console application doesn't have.除非应用程序具有读取控制台应用程序没有的 Windows 消息的功能,否则这将不起作用。 According to the documentation for SystemEvents.SessionSwitch Event :根据SystemEvents.SessionSwitch Event的文档:

This event is only raised if the message pump is running.仅当消息泵正在运行时才会引发此事件。 In a Windows service, unless a hidden form is used or the message pump has been started manually, this event will not be raised.在 Windows 服务中,除非使用隐藏表单或手动启动消息泵,否则不会引发此事件。 For a code example that shows how to handle system events by using a hidden form in a Windows service, see the SystemEvents class.有关显示如何在 Windows 服务中使用隐藏表单来处理系统事件的代码示例,请参阅 SystemEvents class。

If you insist on running this as a console app, check Handling Messages in Console Apps which is a tutorial for running the message pump inside a console application.如果您坚持将其作为控制台应用程序运行,请查看在控制台应用程序中处理消息,这是在控制台应用程序中运行消息泵的教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM