首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WinForm 實作閒置自動鎖定/最小化:GetLastInputInfo 偵測滑鼠鍵盤閒置時間

     編輯:關於.NET

需求

使用者超過指定時間無滑鼠/鍵盤操作,自動鎖定介面 (如最小化視窗),活動恢復則還原。

核心 API:GetLastInputInfo

取得系統上次輸入事件時間 (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 秒無操作最小化,移動滑鼠即還原。可擴充為真正鎖定畫面或登出邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved