【问题标题】:Get Log off event from system从系统获取注销事件
【发布时间】:2010-11-02 08:41:41
【问题描述】:

我正在做一个应用程序,用于在用户注销时清除临时文件、历史记录等。那么我如何知道系统是否要注销(在 C# 中)?

【问题讨论】:

    标签: c# .net wpf logout


    【解决方案1】:

    Environment 类中有一个属性可以告知关闭过程是否已启动:

    Environment.HasShutDownStarted
    

    但经过一番谷歌搜索后,我发现这可能对您有所帮助:

     using Microsoft.Win32;
    
     //during init of your application bind to this event  
     SystemEvents.SessionEnding += 
                new SessionEndingEventHandler(SystemEvents_SessionEnding);
    
     void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
     {
         if (Environment.HasShutdownStarted)
         {
             //Tackle Shutdown
         }
         else
         {
             //Tackle log off
         }
      }
    

    但是如果您只想清除临时文件,那么我认为区分关闭或注销对您没有任何影响。

    【讨论】:

    • 但请记住,在 Vista+ 上,您在关机期间几乎没有时间做任何事情,因此请确保您不能出于任何原因阻止或等待(即尝试删除可能在网络共享等...)
    • 感谢@Paul 那么是否建议在某处输入一个条目,以便 Windows 在下次重新启动或登录时清除这些内容?
    • 什么是系统事件?
    • 关机,注销...使用 Wake On LAN 关机?
    【解决方案2】:

    如果您特别需要注销事件,您可以修改TheVillageIdiot回答中提供的代码如下:

    using Microsoft.Win32;
    
    //during init of your application bind to this event   
    SystemEvents.SessionEnding += 
        new SessionEndingEventHandler(SystemEvents_SessionEnding);
    
    void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e) 
    {     
        if (e.Reason == SessionEndReasons.Logoff) 
        {  
            // insert your code here
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用 WMI 并观察 Type 等于 0 的 Win32_ComputerShutdownEvent。您可以找到有关此事件的更多信息here,以及有关在 .NET 中使用 WMI 的更多信息here

      【讨论】:

        【解决方案4】:

        如果您有 Windows 窗体,您可以处理 FormClosing 事件,然后检查 e.CloseReason 枚举值以确定它是否等于 CloseReason.WindowsShutDown

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.WindowsShutDown)
            {
                // Your code here
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2013-02-19
          • 2023-03-31
          • 2017-11-27
          • 2012-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-09-27
          • 1970-01-01
          相关资源
          最近更新 更多