1

I have a c#(.net) windows service that needs to do something either when windows startup or when user logged in(including back from hibernate). how can the service detect this? any windows events specific for it?

4

1 回答 1

1

对于 windows 启动检查使用Environment.TickCount的简单方法,可能您需要将一些以前的 windows 启动值保存到配置中并与它们进行比较。

当 Environment.TickCount 对您来说还不够或很容易:) 然后使用 WMI:

public void BootTime(){    
    SelectQuery query = new SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE Primary='true'");
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

    foreach (ManagementObject mo in searcher.Get())
    {
        DateTime dtBootTime = ManagementDateTimeConverter.ToDateTime(mo.Properties["LastBootUpTime"].Value.ToString());
        Console.WriteLine(dtBootTime.ToString());
    }
}

要检测登录/注销,如评论之一所述,请使用SystemEvents类和事件SessionSwitch

请注意,它仅在消息泵正在运行时才有效。在 Windows 服务中,除非使用隐藏表单或手动启动消息泵,否则不会引发此事件。

于 2012-05-13T07:43:47.523 回答