检查应用程序是否在一段时间内处于空闲状态并将其锁定

在我的项目中,我需要一个应用程序锁(与windows lock相同)。 如果应用程序空闲一段时间,应该锁定应用程序,即将显示应用程序的登录窗口。 如何在WPF C#应用程序中执行此操作?

您可以使用这些function

  • LockWorkStation
  • GetLastInputInfo

看到这段代码,你必须在表单中添加一个计时器,然后设置this.timer1.Enabled = true;

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsFormsApplication9 { internal struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } public partial class Form1 : Form { [DllImport("User32.dll")] public static extern bool LockWorkStation(); [DllImport("User32.dll")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO Dummy); [DllImport("Kernel32.dll")] private static extern uint GetLastError(); public static uint GetIdleTime() { LASTINPUTINFO LastUserAction = new LASTINPUTINFO(); LastUserAction.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(LastUserAction); GetLastInputInfo(ref LastUserAction); return ((uint)Environment.TickCount - LastUserAction.dwTime); } public static long GetTickCount() { return Environment.TickCount; } public static long GetLastInputTime() { LASTINPUTINFO LastUserAction = new LASTINPUTINFO(); LastUserAction.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(LastUserAction); if (!GetLastInputInfo(ref LastUserAction)) { throw new Exception(GetLastError().ToString()); } return LastUserAction.dwTime; } public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { if (GetIdleTime() > 10000) //10 secs, Time to wait before locking LockWorkStation(); } private void Form1_Load(object sender, EventArgs e) { timer1.Start(); } } } 

IMO接受的答案不如这种方法好:

http://www.codeproject.com/Articles/30345/Application-Idle

CodeProject文章使用Windows消息,这将导致组件认为应用程序不是空闲的 ,例如

 public enum ActivityMessages : int { ///  /// Cursor moved while within the nonclient area. ///  WM_NCMOUSEMOVE = 0x00A0, ///  /// Mouse left button pressed while the cursor was within the nonclient area. ///  WM_NCLBUTTONDOWN = 0x00A1, ///  /// Mouse left button released while the cursor was within the nonclient area. ///  WM_NCLBUTTONUP = 0x00A2, ///  

设置加载超时,每次“活动”动作发生时(您需要连接它们),将计时器重置为开始。