how to detect windows started or user login in c#(

2019-09-16 18:25发布

问题:

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.