判断用户是否在操作

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

 

 

 

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

private struct LASTINPUTINFO
{
public uint cbSize;

public uint dwTime;
}
LASTINPUTINFO lastInPut = new LASTINPUTINFO();


private void timer_Tick(object sender, EventArgs e)
{
//配置时间内无操作锁定
lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
GetLastInputInfo(ref lastInPut);

long noOperationTime = System.Environment.TickCount - lastInPut.dwTime;

if (noOperationTime > 毫秒时间)
{
//退出程序
}

}

转载于:https://www.cnblogs.com/zeroone/archive/2013/03/02/2940428.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值