使用者超過指定時間無滑鼠/鍵盤操作,自動鎖定介面 (如最小化視窗),活動恢復則還原。
取得系統上次輸入事件時間 (dwTime),搭配 Environment.TickCount 計算閒置毫秒數。
public partial class Form1 : Form {
[StructLayout(LayoutKind.Sequential)]
public struct LASTINPUTINFO {
public int cbSize;
public uint dwTime;
}
[DllImport("user32.dll")]
public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public long GetIdleTick() {
var info = new LASTINPUTINFO { cbSize = Marshal.SizeOf(typeof(LASTINPUTINFO)) };
if (!GetLastInputInfo(ref info)) return 0;
return Environment.TickCount - (long)info.dwTime;
}
public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) {
timer1.Interval = 2000; timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e) {
long idle = GetIdleTick();
Text = $"jinjazz說:您已經{idle}ms沒有動了";
if (idle > 10 * 1000) WindowState = FormWindowState.Minimized;
else WindowState = FormWindowState.Normal;
}
}
範例:10 秒無操作最小化,移動滑鼠即還原。可擴充為真正鎖定畫面或登出邏輯。