dee*_*epu 13 .net c# windows-services
我有一个Windows服务,可以获取用户详细信息并将结果保存到日志文本文件中.而且,我的问题是当我关闭或注销我的系统时,我也想将我的系统中的时间保存到该日志文件中.但是,我不知道该怎么做.
我检查了winproc方法来检测关机操作,但我无法在窗口服务上使用它,谷歌搜索发现它只能用于表单.我们如何检测用户是否已点击关机或注销并执行某些操作.所以,请给我一些想法或建议.
我已经将它用于注销,但是当我注销系统时,会在日志条目上进行注销
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
this.RequestAdditionalTime(250000); //gives a 25 second delay on Logoff
if (changeDescription.Reason == SessionChangeReason.SessionLogoff)
{
// Add your save code here
StreamWriter str = new StreamWriter("D:\\Log.txt", true);
str.WriteLine("Service stoped due to " + changeDescription.Reason.ToString() + "on" + DateTime.Now.ToString());
str.Close();
}
base.OnSessionChange(changeDescription);
}
Run Code Online (Sandbox Code Playgroud)
MPe*_*ier 16
要关闭,请覆盖OnShutdown方法:
protected override void OnShutdown()
{
//your code here
base.OnShutdown();
}
Run Code Online (Sandbox Code Playgroud)
注销:
首先,在Service Constructor中向Microsoft.Win32.SystemEvents.SessionEnded添加一个事件处理程序:
public MyService()
{
InitializeComponent;
Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
}
Run Code Online (Sandbox Code Playgroud)
然后添加处理程序:
void SystemEvents_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e)
{
//your code here
}
Run Code Online (Sandbox Code Playgroud)
这应该捕获任何结束的会话,包括控制台本身(运行服务的那个).
小智 12
我知道我是从死里复活的,但我发现它很有帮助,并希望在这个话题上添加一些内容.我正在实现一个托管在Windows服务中的WCF双工库并遇到了这个线程,因为我需要在Windows服务中检测用户注销或关闭计算机的时间.我在Windows 7和Windows 10上使用.Net Framework 4.6.1.就像之前建议的关闭一样,对我有用的是覆盖ServiceBase.OnShutdown()如下:
protected override void OnShutdown()
{
//Your code here
//Don't forget to call ServiceBase OnShutdown()
base.OnShutdown();
}
Run Code Online (Sandbox Code Playgroud)
请记住将以下内容添加到服务的构造函数中以允许捕获关闭事件:
CanShutdown = true;
Run Code Online (Sandbox Code Playgroud)
然后捕获用户注销时,锁定屏幕,切换用户等,您可以OnSessionChange像这样覆盖方法:
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
if (changeDescription.Reason == SessionChangeReason.SessionLogoff)
{
//Your code here...
//I called a static method in my WCF inbound interface class to do stuff...
}
//Don't forget to call ServiceBase OnSessionChange()
base.OnSessionChange(changeDescription);
}
Run Code Online (Sandbox Code Playgroud)
当然记得将以下内容添加到服务的构造函数中以允许捕获会话更改事件:
CanHandleSessionChangeEvent = true;
Run Code Online (Sandbox Code Playgroud)