Delphi 自定义消息拦截


本文整理自网络,侵删。

 
1. 自定义消息拦截
unit UnitMessageHook;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

const
  {定义用于HOOK的消息,也可以是Windows的标准消息}
  WM_TestMessage = WM_USER + 2000;

type
  TForm1 = class(TForm)
    btn1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
var
  HookHandle: HHOOK;

  {Hook处理函数}
function MyFunctionHookPro(Code: Integer; WParam: LongInt; Msg: LongInt): LongInt; stdcall;
begin
  if (Code = HC_ACTION) then
  begin
    if PMsg(Msg)^.message = WM_TestMessage then
    begin
      ShowMessage('已经截获该消息' + PChar(PMsg(Msg)^.WParam));
    end;

  end;
  Result := CallNextHookEx(HookHandle, Code, WParam, LongInt(@Msg));
end;

procedure TForm1.btn1Click(Sender: TObject);
var
  msg: string;
begin
  msg := 'Hello World!';
  {发送特定消息}
  PostMessage(Self.Handle, WM_TestMessage, Integer(PChar(mess)), 0);
end;

{挂钩}
procedure TForm1.FormCreate(Sender: TObject);
begin
  HookHandle := SetWindowsHookEx(WH_GETMESSAGE, @MyFunctionHookPro, HInstance, GetCurrentThreadId);
end;

{摘钩}
procedure TForm1.FormDestroy(Sender: TObject);
begin
  UnhookWindowsHookEx(HookHandle);
end;

end.

 Copied!
以上代码会造成由于内存空间释放而产生乱码

优化代码如下

procedure Send();
var
  mess: string;
  ps: PString;
begin
  New(ps);
  mess := 'Hello World!';
  ps^ := mess;
  {发送特定消息}
  PostMessage(Self.Handle, WM_TestMessage, Integer(PChar(ps)), 0
end;

//接收端
PS := PString(PMsg(Msg)^.WParam);
mess := PS^;
//Do Something
ShowMessage('已经截获该消息' + mess);

//加这一句会导致程序崩溃
Dispose(PS);

来源:http://www.coder163.com/language/delphi/console/钩子原理.html

相关阅读 >>

winapi 字符及字符串函数(7): ischarlower - 是否是个小写字母

Delphi flash控件使用

Delphi设置ie代理的方法

Delphi xe(indy10)tidbytes转ansistring的实现

Delphi整理四(程序控制结构)

Delphi打开外部程序或文件

Delphi 制作资源文件并释放运行

Delphi 判断timage是否为空及注意事项

通过崩溃地址找错误行数之Delphi

Delphi 首字母转换大写

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...