我初学hook,这是改自别人的代码:
请帮看一下改哪:
unit TestHookKey_Unit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
const
WM_HOOKKEY= WM_USER + $1000;
HookDLL = 'Key.dll';
type
THookProcedure=procedure; stdcall;
TForm1 = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FileMapHandle : THandle;
PMem : ^Integer;
HandleDLL : THandle;
HookOn,
HookOff : THookProcedure;
procedure HookKey(var message: TMessage); message WM_HOOKKEY;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.ReadOnly:=TRUE;
Memo1.Clear;
HandleDLL:=LoadLibrary( PChar(ExtractFilePath(Application.Exename)+
HookDll) );
if HandleDLL = 0 then raise Exception.Create('未发现键盘钩子DLL');
@HookOn :=GetProcAddress(HandleDLL, 'HookOn');
@HookOff:=GetProcAddress(HandleDLL, 'HookOff');
IF not assigned(HookOn) or
not assigned(HookOff) then
raise Exception.Create('在给定的 DLL中'+#13+
'未发现所需的函数');
FileMapHandle:=CreateFileMapping( $FFFFFFFF,
nil,
PAGE_READWRITE,
0,
SizeOf(Integer),
'TestHook');
if FileMapHandle=0 then
raise Exception.Create( '创建内存映射文件时出错');
PMem:=MapViewOfFile(FileMapHandle,FILE_MAP_WRITE,0,0,0);
PMem^:=Handle;
HookOn;
end;
procedure TForm1.HookKey(var message: TMessage);
var
KeyName : array[0..100] of char;
Accion, Str : string;
f1, f2, f3: longint;
begin
GetKeyNameText(Message.LParam,@KeyName,100);
Str := String(KeyName);
if not(((Message.lParam shr 31) and 1) = 1) then if not(((Message.lParam shr 30) and 1) = 1) then
begin
Memo1.Lines.text := Memo1.Lines.text + Str;
// 得到当前焦点控减句柄发消息
f1:=GetForegroundWindow;
f2:=GetWindowThreadProcessId(f1,nil);
AttachThreadInput(GetCurrentThreadId,f2,true);
f3:=getfocus;
AttachThreadInput(GetCurrentThreadId,f3,false);
if f3 = 0 then Exit;
SendMessage(f3, $0286,(ord(Str[1]) shl 8) + ord(Str[2]) , 0);
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if Assigned(HookOff) then
HookOff;
if HandleDLL<>0 then
FreeLibrary(HandleDLL);
if FileMapHandle<>0 then
begin
UnmapViewOfFile(PMem);
CloseHandle(FileMapHandle);
end;
end;
end.