先生成一个DLL
-------------------------------------------------------------------------------------
library HookKeyboard;
uses
SysUtils,
Classes,
Windows,
Forms,Graphics;
{$R *.res}
const
MyHookAtom='DarwinZhang_KBH_Atom';
var
HHK:HHook=0;
Form:TForm;
FormHandle,IDEvent
Word;
//定时器函数
procedure MyTimer(hwnd:HWND; umsg,idevent
Word; dwTime
Word); stdcall;
const
DisplayText='text'; //欲显示的内容
var
dc:HDC;
Canvas:TCanvas;
begin
if GetForeGroundWindow=Hwnd then exit;
SetForeGroundWindow(Hwnd);
dc:=GetWindowDC(Hwnd);
Canvas:=TCanvas.Create;
Canvas.Handle:=dc;
Canvas.Font.Color:=clRed;
Canvas.TextOut(0,0,DisplayText); //显示文字
ReleaseDC(Hwnd,dc);
Canvas.Free;
end;
//键盘钩子
function MyKeyboardHook(ncode:Integer; wparam:WParam; lparam:LParam ):LResult; stdcall;
begin
result:=0;
if ncode<0 then begin
CallNextHookEx(HHK,ncode,wparam,lparam);
Exit;
end;
if (lparam shr 31=0) or (wparam<>VK_F11) then exit; //F12键按下
if FindAtom(MyHookAtom)<>0 then exit; //只允许进入一次
AddAtom(MyHookAtom);
Form:=TForm.CreateParented(0);
with Form do begin
BorderStyle:=bsNone;
Width:=80; Height:=20;
Show;
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE or SWP_NOSIZE or SWP_NoACTIVATE);
FormHandle:=Form.Handle;
//万一不行用下面一句
// IDEvent:=SetTimer(FormHandle,FormHandle,200,@MyTimer);
end;
end;
//设置键盘钩子
function SetKeyboardHook:LongBool; stdcall;
begin
if HHK=0 then
HHK:=SetWindowsHookEx(WH_KEYBOARD,@MyKeyboardHook,Hinstance,0);
Result:=HHK<>0;
end;
//撤销键盘钩子
procedure UnHookKeyBoardHook; stdcall;
begin
if HHK=0 then exit;
UnHookWindowsHookEx(HHK);
HHK:=0;
DeleteAtom(FindAtom(MyHookAtom));
KillTimer(FormHandle,IDEvent);
end;
exports
SetKeyBoardHook,
UnHookKeyBoardHook;
begin
end.
再调用
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
const KBDLLName='HookKeyboard.dll';
function SetKeyboardHook:LongBool; stdcall; external KBDLLName;
procedure UnHookKeyBoardHook; stdcall; external KBDLLName;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetKeyboardHook;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
UnHookKeyBoardHook;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
SetKeyboardHook;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
UnHookKeyBoardHook;
end;
end.
不晓得行不行,你试一下.记得用F11键激活。