2012-03-20 128 views
0

我正在使用Windows服务,需要知道本地计算机闲置了多长时间。我已经尝试了标准的Qt方法,但由于该服务是以LocalSystem身份运行的,因此它不会注册本地用户活动。系统空闲时间 - Windows服务

有关如何在应用程序以LocalSystem身份运行时获取机器空闲状态的任何想法?

+0

可能重复(http://stackoverflow.com/questions/6494436 /越来越多的用户空闲时间在C) – 2012-03-20 21:35:58

+0

我会假设你会检测是否有用户登录之前,确定空闲时间... – 2012-03-20 21:40:08

+0

决明子似乎只能与一个终端服务器,而不是本地机器... – user1282008 2012-03-21 16:06:37

回答

0

不知道这是否有帮助。从文章:here

由于我们使用的非托管库,首先出现的额外using语句:?获取用户的空闲时间在C#]的

using System.Runtime.InteropServices; 

// Unmanaged function from user32.dll  
[DllImport("user32.dll")]  
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); 
// Struct we'll need to pass to the function  
internal struct LASTINPUTINFO  
{  
    public uint cbSize;  
    public uint dwTime;  
} 

private void tmrIdle_Tick(object sender, EventArgs e)  
{  
    // Get the system uptime  
    int systemUptime = Environment.TickCount;  
    // The tick at which the last input was recorded  
    int LastInputTicks = 0;  
    // The number of ticks that passed since last input  
    int IdleTicks = 0;    
    // Set the struct  
    LASTINPUTINFO LastInputInfo = new LASTINPUTINFO();  
    LastInputInfo.cbSize = (uint)Marshal.SizeOf(LastInputInfo);  
    LastInputInfo.dwTime = 0;  

    // If we have a value from the function  
    if (GetLastInputInfo(ref LastInputInfo))  
    {  
     // Get the number of ticks at the point when the last activity was seen  
     LastInputTicks = (int)LastInputInfo.dwTime;  
     // Number of idle ticks = system uptime ticks - number of ticks at last input  
     IdleTicks = systemUptime - LastInputTicks;  
    }   

    // Set the labels; divide by 1000 to transform the milliseconds to seconds  
    lblSystemUptime.Text = Convert.ToString(systemUptime/1000) + " seconds";  
    lblIdleTime.Text = Convert.ToString(IdleTicks/1000) + " seconds";  
    lblLastInput.Text = "At second " + Convert.ToString(LastInputTicks/1000);  
} 
+0

我试过了,但它似乎查看LocalSystem的不活动状态,并报告系统自启动以来一直处于非活动状态... – user1282008 2012-03-21 05:12:19

+0

如果您看我的第一条评论在你的问题上,你会看到它使用相同的代码,但是当用户登录时启动这个过程。绝对是一个重复的问题。 – 2012-03-21 17:17:53