gpt4 book ai didi

c# - 在窗口服务中检测关闭

转载 作者:可可西里 更新时间:2023-11-01 08:03:36 25 4
gpt4 key购买 nike

我有一个获取用户详细信息并将结果保存到日志文本文件中的 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);
}

最佳答案

对于关机,覆盖 OnShutdown 方法:

protected override void OnShutdown()
{
//your code here
base.OnShutdown();
}

对于注销:

首先,在Service Constructor中为Microsoft.Win32.SystemEvents.SessionEnded添加一个事件处理器:

public MyService()
{
InitializeComponent;
Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);
}

然后添加处理程序:

void SystemEvents_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e)
{
//your code here
}

这应该捕获任何结束的 session ,包括控制台本身(运行服务的那个)。

关于c# - 在窗口服务中检测关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5202119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com