c# winform 如何得知用户是否正在操作电脑

beambeam 2008-11-20 10:41:03
c# winform 如何得知用户是否正在操作电脑
就像QQ的那个离开状态,当用户离开电脑不操作时,QQ就会检测到用户已离开,这个功能用C#如何做
还有就是不要建议我用全局钩子,因为这样会比较耗资源
...全文
488 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
学习的。。。。
gomoku 2008-11-20
  • 打赏
  • 举报
回复

namespace ActivityMonitor
{
using System;
using System.Runtime.InteropServices;

class ActivityMonitor : System.ComponentModel.Component
{
public void Start()
{
this.isIdle = false;
timer.Elapsed -= Timer_Elapsed;
timer.Elapsed += Timer_Elapsed;
timer.Interval = this.resolution;
timer.Start();
}

public void Stop()
{
timer.Stop();
}

public bool IsIdle
{
get { return this.isIdle; }
private set
{
if (this.isIdle != value)
{
this.isIdle = value;

if (isIdle && OnIdle != null)
{
OnIdle(this, EventArgs.Empty);
}
if (!isIdle && OnActive != null)
{
OnActive(this, EventArgs.Empty);
}
}
}
}

public int IdleTimeOut
{
get { return idleTimeOut; }
set { idleTimeOut = Math.Max(50, value); }
}

public int Resolution
{
get { return resolution; }
set { resolution = Math.Max(50, value); }
}

public event EventHandler OnIdle;
public event EventHandler OnActive;

private void Timer_Elapsed(object sender, EventArgs e)
{
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.size = 8;

if (GetLastInputInfo(ref lastInputInfo))
{
lastActivity = Math.Max(lastActivity, lastInputInfo.lastTick);

int diff = Environment.TickCount - lastActivity;
this.IsIdle = diff > this.IdleTimeOut;
}
}

private bool isIdle = false;
private int idleTimeOut = 5000;
private int resolution = 100;
private int lastActivity = Environment.TickCount;
private System.Timers.Timer timer = new System.Timers.Timer();

[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
public int size;
public int lastTick;
}
[DllImport("User32")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO lii);
}





class UnitTest
{
static void Main()
{
ActivityMonitor monitor = new ActivityMonitor();
monitor.IdleTimeOut = 2000; // 2 seconds
monitor.OnIdle += delegate { Console.WriteLine("On idle"); };
monitor.OnActive += delegate { Console.WriteLine("On active"); };

monitor.Start();
Console.ReadLine();
}
}
}


It's my post on another thread. The monitor doesn't use hook but the GetLastInputInfo API.
我想使用c#做一个 检测键盘 鼠标 空闲状态的程序,请问有什么方法么?

长沙三毛 2008-11-20
  • 打赏
  • 举报
回复
捕获键盘的OnKeyDown事件,捕获MouseMove事件
是是非非 2008-11-20
  • 打赏
  • 举报
回复
汗……“还有就是不要建议我用全局钩子,因为这样会比较耗资源”
才看到这句……
是是非非 2008-11-20
  • 打赏
  • 举报
回复
全局Hook

监控鼠标和键盘动作

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧