开发者

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.

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. According to the documentation for 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. For a code example that shows how to handle system events by using a hidden form in a Windows service, see the 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜