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

  • 相关阅读:
    前端JavaScript中常见设计模式
    第二篇:mybatis核心接口
    [Python进阶] 操纵鼠标:Pynput
    JAVA实现兔子问题--递归
    【AAAI2023】视觉辅助的常识知识获取Visually Grounded Commonsense Knowledge Acquisition 个人学习笔记
    PSO粒子群优化CNN-优化神经网络神经元个数dropout和batch_size等超参数
    对于开发而言,用户体验才是最终的王道(性能优化篇)
    LeetCode琅琊榜第二十层-二进制求和
    精彩分享 | 欢乐游戏 Istio 云原生服务网格三年实践思考
    类和对象8:数值方法
  • 原文地址:https://blog.csdn.net/a00553344/article/details/126382091