在 Delphi 應用程式中偵測使用者閒置狀態(無鍵盤、滑鼠輸入),並在指定秒數後自動關閉或執行特定動作,常用於資訊亭、POS 系統、安全性要求高的桌面應用。本文提供基於 `TApplicationEvents` 或 `THook` 的完整實作方案。
元件面板 → 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.
使用 `SetWindowsHookEx(WH_GETMESSAGE, ...)` 攔獲全系統訊息,適用於 MDI 應用或需跨表單偵測的場景。程式碼較長,核心邏輯同方案一:收到輸入訊息重置計時器。
| 問題 | 原因/解決 |
|---|---|
| 計時器不歸零 | 確認 `ApplicationEvents1` 的 `OnMessage` 事件已正確連結;檢查 `Handled` 是否誤設為 `True` 阻斷訊息傳遞 |
| 最小化到系統匣時仍計時 | 若不希望最小化時觸發,可在 `OnMessage` 中檢查 `IsIconic(Application.Handle)` |
| 遠端桌面/RDP 環境失效 | Hook 方案在 RDP 可能受限;建議改用 `GetLastInputInfo` API(系統級閒置時間) |