【发布时间】:2010-11-02 08:41:41
【问题描述】:
我正在做一个应用程序,用于在用户注销时清除临时文件、历史记录等。那么我如何知道系统是否要注销(在 C# 中)?
【问题讨论】:
我正在做一个应用程序,用于在用户注销时清除临时文件、历史记录等。那么我如何知道系统是否要注销(在 C# 中)?
【问题讨论】:
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
}
}
但是如果您只想清除临时文件,那么我认为区分关闭或注销对您没有任何影响。
【讨论】:
如果您特别需要注销事件,您可以修改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
}
}
【讨论】:
如果您有 Windows 窗体,您可以处理 FormClosing 事件,然后检查 e.CloseReason 枚举值以确定它是否等于 CloseReason.WindowsShutDown。
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.WindowsShutDown)
{
// Your code here
}
}
【讨论】: