C# 从系统获取注销事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/984881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Log off event from system
提问by Sauron
I am doing an application which is used to clear the Temp files, history etc, when the user log off. So how can I know if the system is going to logoff (in C#)?
我正在做一个应用程序,用于在用户注销时清除临时文件、历史记录等。那么我怎么知道系统是否要注销(在 C# 中)?
采纳答案by TheVillageIdiot
There is a property in Environmentclass that tells about if shutdown process has started:
Environment类中有一个属性可以说明关闭过程是否已启动:
Environment.HasShutDownStarted
But after some googling I found out that this may be of help to you:
但经过一番谷歌搜索后,我发现这可能对您有所帮助:
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
}
}
But if you only want to clear temp file then I think distinguishing between shutdown or log off is not of any consequence to you.
但是,如果您只想清除临时文件,那么我认为区分关机或注销对您没有任何影响。
回答by jrista
回答by bjh
If you specifically need the log-off event, you can modify the code provided in TheVillageIdiot's answer as follows:
如果你特别需要注销事件,你可以修改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
}
}
回答by riofly
If you have a Windows Form, you can handle the FormClosing
event, then check the e.CloseReason
enum value to determine if it equals to CloseReason.WindowsShutDown
.
如果您有Windows Form,则可以处理该FormClosing
事件,然后检查e.CloseReason
枚举值以确定它是否等于CloseReason.WindowsShutDown
。
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.WindowsShutDown)
{
// Your code here
}
}