«« Site Rescued »»

While the site is still going to move from its current host, a new site will now take its place. More Info.

The new site may have less content, but the core will now remain. And it will now play nicely with phones! Keep an eye on the DelphiDabbler Blog for news.

» Help

How to trap the ALT key state in a visual component

   
Question
I'd like to trap the ALT Key state in a visual component to display the status. So any pressing of the key in any other component should be visible in this component.

You could install a window hook procedure and execute your code each time the ALT key was pressed. Below is a simple example:

{ ... }
type
  TTestEdit = class(TEdit)
  protected
    procedure CreateWnd; override;
    procedure DestroyWnd; override;
  end;

{ ... }

var
  Hook: HHook;

function GetMsgHook(nCode: Integer; wParam: longint;
  lParam: longint): longint; stdcall;
begin
  if wParam = VK_MENU then
    ShowMessage('alt');
  Result := CallNextHookEx(Hook, nCode, wParam, lParam);
end;

procedure TTestEdit.CreateWnd;
begin
  inherited CreateWnd;
  if (Hook = 0) and not (csDesigning in ComponentState) then
    Hook := SetWindowsHookEx(
      WH_KEYBOARD, GetMsgHook, Hinstance,
      GetWindowThreadProcessId(Handle, nil)
    );
end;

procedure TTestEdit.DestroyWnd;
begin
  if Hook <> 0 then
  begin
    UnhookWindowsHookEx(Hook);
    Hook := 0;
  end;
  inherited DestroyWnd;
end;

initialization
  Hook := 0;
Original resource: The Delphi Pool
Author: Serge Gubenko
Added: 2009-08-12
Last updated: 2009-08-12

« Return to contents »