如何检测Windows启动或c#(.net)Windows服务中的用户登录? [英] how to detect windows started or user login in c#(.net) windows service?

查看:102
本文介绍了如何检测Windows启动或c#(.net)Windows服务中的用户登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c#(.net)Windows服务,需要在Windows启动时或用户登录时(包括从休眠状态返回)执行某些操作.服务如何检测到这一点?是否有任何特定于Windows的事件?

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?

推荐答案

对于Windows启动,请检查使用

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.

当Environment.TickCount对您来说不够用或很简单时:)然后使用WMI:

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());
    }
}

要检测注释之一中所说的登录/注销,请使用 SystemEvents 类和事件

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

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

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.

这篇关于如何检测Windows启动或c#(.net)Windows服务中的用户登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆