+ -
当前位置:首页 → 问答吧 → 我想不用DLL,做一个局部钩子,就是钩当前程序的回车键,下面代码就是不行,帮助我看看。

我想不用DLL,做一个局部钩子,就是钩当前程序的回车键,下面代码就是不行,帮助我看看。

时间:2011-11-24

来源:互联网

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, keyboardhook;

type
  TForm1 = class(TForm)
  btn1: TButton;
  btn2: TButton;
  memo1: TMemo;
  procedure btn1Click(Sender: TObject);
  procedure btn2Click(Sender: TObject);
  private
  { Private declarations }
  public
  { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
begin
  StopKeyBoardHook;
end;

procedure TForm1.btn2Click(Sender: TObject);
begin
  setKeyBoardHook;
end;


end.
============================================
unit KeyBoardHook;

interface

uses
  SysUtils, Windows, Messages, Classes;

function KeyBoardHookProc(code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
procedure SetKeyBoardHook;stdcall;
procedure StopKeyBoardHook;stdcall;

implementation

type
  PKBDLLHOOKSTRUCT=^KBDLLHOOKSTRUCT;
  KBDLLHOOKSTRUCT=record
  vkCode:DWORD;
  scanCode:DWORD;
  flags:DWORD;
  time:DWORD;
  dwExtraInfo:DWORD;
  end;
const
  WH_KEYBOARD_LL=13;
var
  hook:HHOOK=0;

//回调过程
function KeyBoardHookproc(code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
  PKBDLLHook:PKBDLLHOOKSTRUCT;
begin
  //如果有键盘动作
  if code = HC_ACTION then
  begin
  if (wParam=WM_KeyDown) then
  begin
  PKBDLLHook:=PKBDLLHOOKSTRUCT(lParam);
  if PKBDLLHook^.vkCode = vk_return then
  begin
  RESULT:=1;//屏蔽了按键消息的传递
  Exit;
  end;
  end;
  end;
  //将按键消息传递给别的线程
  Result:=CallNextHookEx(hook,Code,wParam,lParam);
end;

procedure setKeyBoardHook;stdcall;
begin
  //挂钩,这里没有做挂钩失败的提示
  if hook = 0 then begin
  hook:=SetWindowsHookEx(WH_KEYBOARD,@KeyBoardHookProc,hInstance,0);//
  MessageBox(0, PChar(IntToStr(hook)), 'b', 0);
  end;
end;

procedure stopKeyBoardHook;stdcall;
begin
  //摘钩
  if hook<>0 then begin
  UnhookWindowsHookEx(hook);
  hook:=0;
  end;

end;



end.

作者: Chengs_bbs   发布时间: 2011-11-24

你自己程序的还要钩子干嘛啊

如果你就一个界面的话,就更简单了,直接form1的keypreview设成true,然后keypress事件里面
if key = #13 then
  showmessage('oh yeah!');

作者: skylkj   发布时间: 2011-11-24

这个只是一个测试,要用钩子。

作者: Chengs_bbs   发布时间: 2011-11-24