题
我正在执行一个应用程序,用于清除临时文件,历史记录等,当用户注销时。那么,我怎么知道系统是否将在C#中注销?
解决方案
有一个财产 环境 讲述关闭过程是否已经开始的课程:
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
}
}
但是,如果您只想清除临时文件,那么我认为区分关闭或注销对您来说并不是任何结果。
其他提示
如果您特别需要注销事件,则可以修改VillageIdiot在答案中提供的代码如下:
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
}
}
不隶属于 StackOverflow