在程序内部hook键盘的话主要调用SetWindowsHookEx这个函数。
例子如下:用按键在image上画线。
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
KBhook: Hhook;
cx, cy : integer;
function KeyboardHookProc(code: Integer; WordParam: Word; LongParam: LongInt):LongInt; stdcall;
{declaring a callback}
implementation
{$R *.dfm}
function KeyboardHookProc(Code: Integer; WordParam: Word; LongParam: LongInt): LongInt;
begin
case WordParam of
vk_Space:
begin
with Form1.Image1.Canvas do
begin
Brush.Color := clWhite;
Brush.Style := bsSolid;
FillRect(Form1.Image1.ClientRect)
end;
end;
vk_Right: cx := cx+1;
vk_Left: cx := cx-1;
vk_Up: cy := cy-1;
vk_Down: cy := cy+1;
end; {case}
If cx < 2 then cx := Form1.Image1.ClientWidth-2;
If cx > Form1.Image1.ClientWidth -2 then cx := 2;
If cy < 2 then cy := Form1.Image1.ClientHeight -2 ;
If cy > Form1.Image1.ClientHeight-2 then cy := 2;
with Form1.Image1.Canvas do
begin
Pen.Color := clRed;
Brush.Color := clYellow;
TextOut(0,0,Format('%d, %d',[cx,cy])) ;
Rectangle(cx-2, cy-2, cx+2, cy+2) ;
end;
Result:=0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
{Set a keyboard hook so we can hook keyboard input}
KBHook:=SetWindowsHookEx(WH_KEYBOARD,
{callback >} @KeyboardHookProc,
HInstance,
GetCurrentThreadId()) ;
{put the warship in the center of the screen}
cx := Image1.ClientWidth div 2;
cy := Image1.ClientHeight div 2;
Image1.Canvas.PenPos := Point(cx,cy);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
UnHookWindowsHookEx(KBHook) ;
end;
end.