萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Delphi 實作程式閒置 30 秒無鍵盤滑鼠動作自動關閉

在 Delphi 應用程式中偵測使用者閒置狀態(無鍵盤、滑鼠輸入),並在指定秒數後自動關閉或執行特定動作,常用於資訊亭、POS 系統、安全性要求高的桌面應用。本文提供基於 `TApplicationEvents` 或 `THook` 的完整實作方案。

方案一:使用 TApplicationEvents(最簡單、VCL 原生)

元件面板 → Additional → `TApplicationEvents` 拖放到表單,設定 `OnMessage` 事件。

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, AppEvnts; // 需引用 AppEvnts

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Timer1: TTimer;
    ApplicationEvents1: TApplicationEvents;
    procedure Timer1Timer(Sender: TObject);
    procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
    procedure Button1Click(Sender: TObject);
  private
    FIdleSeconds: Integer;
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
begin
  // 攔獲滑鼠移動、鍵盤按下、滑鼠點擊等訊息
  if (Msg.message = WM_MOUSEMOVE) or
     (Msg.message = WM_LBUTTONDOWN) or (Msg.message = WM_RBUTTONDOWN) or
     (Msg.message = WM_KEYDOWN) or (Msg.message = WM_SYSKEYDOWN) then
  begin
    FIdleSeconds := 0; // 重置閒置計數
  end;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Inc(FIdleSeconds);
  Memo1.Lines.Add(Format('閒置 %d 秒', [FIdleSeconds]));
  if FIdleSeconds >= 30 then
  begin
    Timer1.Enabled := False;
    Close; // 或執行登出、鎖定畫面等邏輯
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Close;
end;

end.

方案二:全域 Hook(適用於多表單、無焦點也能偵測)

使用 `SetWindowsHookEx(WH_GETMESSAGE, ...)` 攔獲全系統訊息,適用於 MDI 應用或需跨表單偵測的場景。程式碼較長,核心邏輯同方案一:收到輸入訊息重置計時器。

關鍵參數設定

  • `Timer1.Interval := 1000`(1 秒觸發一次)
  • 閒置門檻:`FIdleSeconds >= 30` 代表 30 秒
  • 攔截訊息類型:`WM_MOUSEMOVE`, `WM_LBUTTONDOWN`, `WM_RBUTTONDOWN`, `WM_KEYDOWN`, `WM_SYSKEYDOWN`(含 Alt 鍵)

進階擴充建議

  1. 顯示倒數視窗:最後 10 秒顯示倒數提醒,使用者動作可取消。
  2. 記錄閒置日誌:寫入資料庫/檔案,供稽核追蹤。
  3. 多監視器支援:`WM_MOUSEMOVE` 涵蓋所有螢幕座標。
  4. 排除特定視窗:若某對話框不應重置計時(如「確認儲存?」),可在 Hook 中判斷視窗類別/標題決定是否重置。

常見問題

替代方案:GetLastInputInfo(系統級,無需 Hook)

function GetIdleTime: DWORD;
var
  LastInput: TLastInputInfo;
begin
  LastInput.cbSize := SizeOf(TLastInputInfo);
  if GetLastInputInfo(LastInput) then
    Result := GetTickCount - LastInput.dwTime
  else
    Result := 0;
end;

// Timer 中呼叫
if GetIdleTime >= 30000 then Close; // 30 秒 = 30000 ms
`GetLastInputInfo` 取得的是「全系統最後輸入時間」,不分應用程式,適合單一用途機台(Kiosk 模式)。

根據應用場景選擇:單表單用 `TApplicationEvents`,多表單/跨視窗用 Hook,Kiosk 模式用 `GetLastInputInfo`。

copyright © 萬盛學電腦網 all rights reserved
問題原因/解決
計時器不歸零確認 `ApplicationEvents1` 的 `OnMessage` 事件已正確連結;檢查 `Handled` 是否誤設為 `True` 阻斷訊息傳遞
最小化到系統匣時仍計時若不希望最小化時觸發,可在 `OnMessage` 中檢查 `IsIconic(Application.Handle)`
遠端桌面/RDP 環境失效Hook 方案在 RDP 可能受限;建議改用 `GetLastInputInfo` API(系統級閒置時間)