系统空闲时间 - Windows服务

时间:2012-03-20 21:34:23

标签: c# windows-services

我正在开发Windows服务,需要知道本地计算机空闲了多长时间。我尝试过标准的Qt方法,但由于服务是作为LocalSystem运行的,因此它不会注册本地用户活动。

当应用程序作为LocalSystem运行时,有关如何获取计算机空闲状态的任何想法吗?

1 个答案:

答案 0 :(得分:0)

不确定这是否有帮助。来自文章:here

由于我们使用的是非托管库,首先是附加的using语句:

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