how to detect windows started or user login in c#(.net) windows service?

99封情书 提交于 2019-12-24 19:46:33

问题


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?


回答1:


For windows startup check the easeist way to use Environment.TickCount, and probably you need to save some previous windows startup values into config and compare with them.

When Environment.TickCount is not enough for you or very easy :) Then use 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());
    }
}

To detect log-on/log-off as it was said in one of comments use SystemEvents class, and event SessionSwitch.

Please note that it works only if the message pump is running. In a Windows service, unless a hidden form is used or the message pump has been started manually, this event will not be raised.



来源:https://stackoverflow.com/questions/10554922/how-to-detect-windows-started-or-user-login-in-c-net-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!