如何判断Windows何时处于非活动状态 [英] How to tell when Windows is inactive

查看:503
本文介绍了如何判断Windows何时处于非活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只有当您一段时间不使用计算机时,各种程序才能执行操作(例如屏幕保护程序,Google桌面索引编制等)。

Various programs can do stuff only when you haven't used the computer for a while (eg screensaver, Google Desktop indexing, etc).

他们怎么知道什么时候不活跃? Windows中是否有一些功能可以告诉您它已停用了多长时间,还是您必须使用某种键盘/鼠标挂钩来自己跟踪活动?

How do they know when it has been inactive? Is there some function in Windows that tells you how long it has been inactive, or do you have to use some kind of keyboard/mouse hook to track activity yourself?

I正在使用C#,但是我对确定不活动状态的任何方法都感兴趣。

I'm using C#, but I'm interested in any method of determining the inactivity.

推荐答案

编辑:更改了答案,提供了文字以及Shy的答案背后的细节(应该并且已经被接受)。随时合并和删除此版本。

changed answer, providing text and detail behind Shy's answer (which should be and was accepted). Feel free to merge and delete this one.

GetLastInputInfo 函数
GetLastInputInfo函数检索上一次输入事件的时间。

GetLastInputInfo Function The GetLastInputInfo function retrieves the time of the last input event.

在P / Invoke中粘贴

Pasted here from P/Invoke

此函数检索自上次用户输入以来的时间

This function retrieves the time since last user input

[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

static int GetLastInputTime()
{
    int idleTime = 0;
    LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
    lastInputInfo.cbSize = Marshal.SizeOf( lastInputInfo );
    lastInputInfo.dwTime = 0;

    int envTicks = Environment.TickCount;

    if( GetLastInputInfo( ref lastInputInfo ) )
    {
    int lastInputTick = lastInputInfo.dwTime;

    idleTime = envTicks - lastInputTick;
    }

    return (( idleTime > 0 ) ? ( idleTime / 1000 ) : idleTime );
}

[StructLayout( LayoutKind.Sequential )]
struct LASTINPUTINFO
{
    public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));

    [MarshalAs(UnmanagedType.U4)]
    public int cbSize;    
    [MarshalAs(UnmanagedType.U4)]
    public UInt32 dwTime;
}


FWIW:
我实施了AnAppADay中的全局键盘和鼠标钩。请参阅此应用的来源-与您想要的非常接近。您需要的类位于AnAppADay.Utils命名空间中。
[由于linkrot而刮擦]

FWIW: I implemented a global keyboard and mouse hook during AnAppADay. See this app for the source - it's pretty close to what you want. The classes you'll want are in the AnAppADay.Utils namespace. [scratched due to linkrot]

这篇关于如何判断Windows何时处于非活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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