程序内hook键盘

在程序内部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.
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值