主要需要解決兩個問題,即隐藏視窗和設定熱鍵。
一. 隐藏視窗
通過API函數GETACTIVEWINDOW擷取目前視窗;函數ShowWindow(HWND,nCmdShow)的參數nCmdShow取SW_HIDE時将之隐藏,取SW_SHOW時将之顯示。例如:showwindow(getactivewindow,sw_hide)。隐藏好窗體後,須記住窗體句柄以便恢複。
二. 鍵盤監控
為了實作鍵盤監控須用到鈎子。
以下是程式的源檔案:
---HKHide.pas---
unit HKHide;
interface
uses
Windows, Messages, sysutils;
var
hNextHookHide: HHook;
HideSaveExit: Pointer;
hbefore:longint;
function KeyboardHookHandler(iCode: Integer;wParam: WPARAM;
lParam: LPARAM): LRESULT; stdcall; export;
function EnableHideHook: BOOL; export;
function DisableHideHook: BOOL; export;
procedure HideHookExit; far;
implementation
const _KeyPressMask = $80000000;
f:textfile;
temp:string;
begin
Result := 0;
If iCode < 0 Then
begin
Result := CallNextHookEx(hNextHookHide, iCode, wParam, lParam);
Exit;
end;
// 偵測 Ctrl + Alt + F12 組合鍵
if ((lParam and _KeyPressMask) = 0) //按下時生效
and (GetKeyState(vk_Control) < 0)
and (getkeystate(vk_menu)<0) and (wParam = vk_F12) then
Result := 1;
//檔案不存在則建立
if not fileexists(c:\test.txt) then
begin
assignfile(f,c:\test.txt);
rewrite(f);
writeln(f,0);
closefile(f);
end
else begin
reset(f);
readln(f,temp);
hbefore:=strtoint(temp);
begin
hbefore:=getactivewindow;
temp:=inttostr(hbefore);
rewrite(f);
writeln(f,temp);
closefile(f);
ShowWindow(hbefore, SW_HIDE);
end
else begin
showwindow(hbefore,sw_show);
writeln(f,0);
end;
end;
end;
Result := False;
if hNextHookHide <> 0 then Exit;
// 挂上 WH_KEYBOARD 這型的 HOOK, 同時, 傳回值必須保留下
// 來, 免得 HOOK 呼叫鍊結斷掉
hNextHookHide := SetWindowsHookEx(WH_KEYBOARD,
KeyboardHookHandler,HInstance,0);
Result := hNextHookHide <> 0;
if hNextHookHide <> 0 then
Result:=True;
UnhookWindowshookEx(hNextHookHide); // 解除 Keyboard Hook
hNextHookHide:=0;
end
else
Result:=False;
procedure HideHookExit;
// 如果忘了解除 HOOK, 自動代了解除的動作
if hNextHookHide <> 0 then DisableHideHook;
ExitProc := HideSaveExit;
end.
---HKPHide.dpr---
library HKPHide;
HKHide in HKHide.pas;
exports
EnableHideHook,
DisableHideHook;
hNextHookHide := 0;
hbefore:=0;
HideSaveExit := ExitProc;
ExitProc := @HideHookExit;
檔案制作好後選Build All編譯成HKPHide.dll。
建立一個工程Project1
---Unit1.pas---
unit Unit1;
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Form1: TForm1;
{$R *.DFM}
function EnableHideHook: BOOL; external HKPHide.DLL;
function DisableHideHook: BOOL; external HKPHide.DLL;
procedure TForm1.Button1Click(Sender: TObject);
if EnableHideHook then
ShowMessage(HotKey Testing...);
procedure TForm1.Button2Click(Sender: TObject);
if DisableHideHook then
ShowMessage(HotKey Testing..., DONE!!);
運作程式按Button1後啟動鈎子,這時運作其他程式,按Ctrl+Alt+F12可将之隐藏,再按一下則恢複。以下程式在Delphi 4下通過。