Board index » delphi » Intercepting ALL Keyboard events

Intercepting ALL Keyboard events

I'd like to intercept all keypresses even though my delphi application
is not the one who has the focus. The OnKey event only gets called
when the application is active.

I've tried with SetWindowsHookEx in combination with the callback
function KeyboardProc, but it terminates with a GPF. In the help file
it says something about that the callback function must reside in a
DLL. Why?

Can anyone point me in the direction on how to do this? Has anyone
allready done this?

(Windows 3.11 by the way)

Thanks,
//Per
----
Per Magnusson, ABB Network Partner AB
Email: rlyp...@rly.abb.se

 

Re:Intercepting ALL Keyboard events


Quote
Per Magnusson wrote:

> I'd like to intercept all keypresses even though my delphi application
> is not the one who has the focus. The OnKey event only gets called
> when the application is active.

> I've tried with SetWindowsHookEx in combination with the callback
> function KeyboardProc, but it terminates with a GPF. In the help file
> it says something about that the callback function must reside in a
> DLL. Why?

> Can anyone point me in the direction on how to do this? Has anyone
> allready done this?

        Happen to have a mouse hook demo handy - a keyboard hook should
work more or less the same. Make a dll like so:

library Hookdemo;

uses

  Beeper in '\DELDEMOS\HOOKDEMO\BEEPER.PAS';

exports
       SetHook index 1,
       UnHookHook index 2,
       HookProc index 3;

begin
   HookedAlready:=False;
end.

, where beeper.pas is like so:

unit Beeper;

interface

uses Wintypes,Winprocs,Messages;

function SetHook:Boolean;export;
function UnHookHook:Boolean;export;
function HookProc(Code:integer; wParam: Word; lParam: Longint): Longint;export;

var HookedAlready:Boolean;

implementation

var
   ourHook:HHook;

function SetHook:Boolean;
begin
if HookedAlready then exit;
ourHook:=SetWindowsHookEx(WH_MOUSE,HookProc,HInstance,0);
HookedAlready:=True;
end;

function UnHookHook:Boolean;
begin
UnHookWindowsHookEx(ourHook);
HookedAlready:=False;
end;

function HookProc(Code:integer; wParam: Word; lParam: Longint): Longint;
begin
   if (wParam=WM_LBUTTONDOWN) then MessageBeep(0);
   result:=CallNextHookEx(ourHook,Code,wParam,lParam);
end;

end.

        Now if you call the SetHook function from an application there's a
beep everytime you press the left mouse button - this continues until you
call the UnHookHook function.
        In an actual application you're supposed to call CallNextHookEx
immediately and do nothing else if code < 0 .

--
David Ullrich

?his ?s ?avid ?llrich's ?ig ?ile
(Someone undeleted it for me...)

Other Threads