簡體   English   中英

使用 c# 檢測注銷時出現問題

[英]problem in detecting logoff using c#

我試圖檢測注銷事件並將其寫入文本。

如何解決這個問題? 我想在文本文件中寫入注銷時間,但是當我注銷 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();
    }
}

除非應用程序具有讀取控制台應用程序沒有的 Windows 消息的功能,否則這將不起作用。 根據SystemEvents.SessionSwitch Event的文檔:

僅當消息泵正在運行時才會引發此事件。 在 Windows 服務中,除非使用隱藏表單或手動啟動消息泵,否則不會引發此事件。 有關顯示如何在 Windows 服務中使用隱藏表單來處理系統事件的代碼示例,請參閱 SystemEvents class。

如果您堅持將其作為控制台應用程序運行,請查看在控制台應用程序中處理消息,這是在控制台應用程序中運行消息泵的教程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM