unit HotKeyUnit;
{
Global Hotkey class by Martin Pelletier
You have the rights to use & modify this class for your
own needs. All I ask is, if you make a modification to this
class, please send me a copy by e-mail at pemartin@videotron.ca
}
interface
uses Windows, Classes, Messages, Forms, Sysutils;
type
THgeHotKey = class(TComponent)
private
FRegistered : Boolean;
FID : Integer;
FHotkey: string;
FOnHotkey: TNotifyEvent;
FMsgWindow: HWnd;
procedure SetHotkey(const Value: string);
procedure SetOnHotkey(const Value: TNotifyEvent);
protected
procedure MsgWndProc( var Msg: TMessage );
public
constructor Create(AOwner : TComponent); overload; override;
constructor Create(AOwner : TComponent; AHotkey : string); reintroduce; overload;
destructor Destroy; override;
property Hotkey : string read FHotkey write SetHotkey;
property OnHotkey : TNotifyEvent read FOnHotkey write SetOnHotkey;
end;
implementation
{ THokey }
constructor THgeHotkey.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRegistered := False;
FID := 100; // Hotkey ID see RegisterHotKey API for reference
FMsgWindow := AllocateHWnd(MsgWndProc);
end;
constructor THgeHotkey.Create(AOwner: TComponent; AHotkey: string);
begin
inherited Create(AOwner);
FRegistered := False;
FID := 100; // Hotkey ID see RegisterHotKey API for reference
FMsgWindow := AllocateHWnd(MsgWndProc);
SetHotKey(AHotkey);
end;
destructor THgeHotkey.Destroy;
begin
if FRegistered then
UnregisterHotKey(FMsgWindow, FID);
DeallocateHWnd(FMsgWindow);
inherited Destroy;
end;
procedure THgeHotkey.MsgWndProc(var Msg: TMessage);
begin
with Msg do
begin
if (Msg = WM_HOTKEY) and (WParam = FID) then
if Assigned(OnHotKey) then
OnHotKey(Self);
end;
Dispatch(Msg);
end;
procedure THgeHotkey.SetHotkey(const Value: String);
begin
FHotkey := Value;
if FRegistered then
begin
UnregisterHotKey(FMsgWindow, FID);
FRegistered := False;
end;
{
In this class only ALT hotkey can be created. See the
RegisterHotKey API in help for additional information
}
if RegisterHotKey(FMsgWindow, FID, MOD_ALT, Cardinal(FHotKey[1])) then
FRegistered := True
else
Raise Exception.Create('Cannot create ALT_' + FHotKey + ' hotkey');
end;
procedure THgeHotkey.SetOnHotkey(const Value: TNotifyEvent);
begin
FOnHotkey := Value;
end;
end.