![]() ![]() ![]() ![]() |
|||||
|
|||||
樓主 ColorWind ![]()
![]() |
上網找了資料嘗試以下程式碼, 本來在自己兩台筆電(Win10)測試沒問題, 後來換到其他電腦(Win7和Win10都有)就無法順利偵測。 無法偵測的情況,大概就是滑鼠一直移動但是偵測不到,或者成功偵測幾秒就又失效了。 想請各位高手幫忙看看哪裡有問題?或是這個方法有什麼限制嗎? 感謝~!! 附上測試功能用的程式碼, 1. 在WinForm上面放一個計時器和TextBox, 2. 程式啟動後計時器開始每1秒偵測一次滑鼠鍵盤的Idle狀態 3. 如果非Idle就把當前時間放到TextBox內 [code] using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsFormsApplication10 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { LastInputTime = DateTime.Now; timer1.Interval = 100;//設定計時器幾毫秒執行一次 timer1.Enabled = true;//打開器 } # region "抓取滑鼠鍵盤最後操作時間" private struct LASTINPUTINFO { [MarshalAs(UnmanagedType.U4)] public int cbSize; [MarshalAs(UnmanagedType.U4)] public uint dwTime; } [DllImport("user32.dll")] private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); public static long GetIdleTick() { LASTINPUTINFO lastInputInfo = new LASTINPUTINFO(); lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo); if (!GetLastInputInfo(ref lastInputInfo)) return 0; // not Idle else return Environment.TickCount - (long)lastInputInfo.dwTime; // Idle Time } #endregion DateTime LastInputTime; private void timer1_Tick(object sender, EventArgs e) { // 非Idle, 紀錄最後操作時間 if (GetIdleTick() == 0) LastInputTime = DateTime.Now; textBox1.Text = LastInputTime.ToString(); } } } [/code] |