windows 检测用户活动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5244943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting User Activity
提问by Sally
I need to create a program that monitors a computer for activity. Such as a mouse move, mouse click or keyboard input. I don't need to record what has happened just that the computer is in use. If their computer has not been in use for a certain period of time, i.e. 15 mins, I need to fire off an event.
我需要创建一个程序来监视计算机的活动。例如鼠标移动、鼠标点击或键盘输入。我不需要只记录计算机正在使用中发生的事情。如果他们的计算机有一段时间没有使用,即 15 分钟,我需要触发一个事件。
Is there a way that I can get notified of these events?
有没有办法让我收到这些事件的通知?
采纳答案by Ken D
Check this articlewhich can get the idle time of the computer, and then you would fire your event on an arbitrary condition.
查看这篇文章,它可以获得计算机的空闲时间,然后您可以在任意条件下触发您的事件。
Pseudo-Code:
伪代码:
If Computer_is_Idle > 15 minutes Then
Do this
Else
Do that or Wait more...
Note:Source code available within the article.
注意:文章中提供了源代码。
回答by Murat Atasoy
Thank you LordCover. This code is from here. This class takes control of the keyboard and mouse controls for you. You can use in a timer like this:
谢谢楼主。这段代码来自这里。此类为您控制键盘和鼠标控件。您可以在这样的计时器中使用:
private void timer1_Tick(object sender, EventArgs e)
{
listBox1.Items.Add(Win32.GetIdleTime().ToString());
if (Win32.GetIdleTime() > 60000) // 1 minute
{
textBox1.Text = "SLEEPING NOW";
}
}
Main code for control. Paste to your form code.
控制的主要代码。粘贴到您的表单代码。
internal struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
public class Win32
{
[DllImport("User32.dll")]
public static extern bool LockWorkStation();
[DllImport("User32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[DllImport("Kernel32.dll")]
private static extern uint GetLastError();
public static uint GetIdleTime()
{
LASTINPUTINFO lastInPut = new LASTINPUTINFO();
lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
GetLastInputInfo(ref lastInPut);
return ((uint)Environment.TickCount - lastInPut.dwTime);
}
public static long GetLastInputTime()
{
LASTINPUTINFO lastInPut = new LASTINPUTINFO();
lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
if (!GetLastInputInfo(ref lastInPut))
{
throw new Exception(GetLastError().ToString());
}
return lastInPut.dwTime;
}
}
回答by Jon
You need to set a global keyboard hook and a global mouse hook. This will result in all keyboard and mouse activity being passed to your application. You can remember the time of the last such event, and check periodically if more than your example 15 minutes have passed since that time.
您需要设置全局键盘挂钩和全局鼠标挂钩。这将导致所有键盘和鼠标活动都传递给您的应用程序。您可以记住上次此类事件的时间,并定期检查自该时间以来是否已超过您示例的 15 分钟。
Take a look herefor an example project. You may also find thisuseful.