Link to home
Start Free TrialLog in
Avatar of nrico
nrico

asked on

Catch keys

How can I make my Delphi program running in the back intercept keystrokes that were not meant for it? (Like making it pop up at a certain combo)
ASKER CERTIFIED SOLUTION
Avatar of thomasphlips
thomasphlips

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nrico
nrico

ASKER

A little explanation would be useful :-). What does it do, how does it work?
Just use RegisterHotKey!
It is sooo much easier.

Something like this:
THotKey is the component on the Win32 page in the palette.

procedure TForm1.SetHotKey(txtHotKey: THotKey);
  var Mods: UINT;
      VKey: UINT;
  begin
    Mods := 0;
    if hkShift in txtHotKey.Modifiers then
      Mods := Mods or MOD_SHIFT;
    if hkCtrl in txtHotKey.Modifiers then
      Mods := Mods or MOD_CONTROL;
    if hkAlt in txtHotKey.Modifiers then
      Mods := Mods or MOD_ALT;
    VKey := txtHotKey.HotKey and $FF;
    if VKey <> 0 then
      begin
        RegisterHotKey(Application.Handle, 1299, Mods, VKey);
      end
    else
      begin
        RegisterHotKey(Application.Handle, 1299, 0, 0);
      end;
  end;



Add this to public part of the declaration of your main form:
    procedure AppMessage(var Msg: TMsg; var Handled: Boolean);


In the FormCreate event, type this:
    Application.OnMessage := AppMessage;


Supply the AppMessage function:
procedure TForm1.AppMessage(var Msg: TMsg; var Handled: Boolean);
  var CursorPos: TPoint;
  begin
    if Msg.Message = WM_HOTKEY then
      begin
        //Do your stuff here
        //The HiWord of lParam is the virtual key code (eg. VK_TAB)
        //LoWord of lParam contains modifiers ctrl, alt, shift
        //See WM_HOTKEY for help
        Handled := true;
      end
    else
      begin
        Handled := false;
      end;
  end;


Also, you are supposed to call UnregistryHotKey somewhere too.
I should mention that you don't need to use the THotKey component. You can just put the call to RegisterHotKey in your FormCreate event if you want.
Also, 1299 is just a random number to identify the registration.
Use is to unregister in the FormDestroy event:
UnregistryHotKey(Application.Handle, 1299);
It probably makes sense to make it a unit local constant.
huh ? he accepted the other answer.. ?

Avatar of nrico

ASKER

Right. I want to catch ALL keys, not just a hotkey.