解决方法
这样做你想要的.
首先,您需要一个在后台运行的程序,并监听并响应击键.像这样:
program Project1; uses Windows,Messages,ShellAPI; var W: HWND; M: MSG; const WM_SETHOTKEY = WM_APP + 1; WM_UNSETHOTKEY = WM_APP + 2; AppName = 'Rejbrand Hot Key Listener'; const FileNames: array[0..1] of string = ('notepad.exe','pbrush.exe'); begin if FindWindow('STATIC',PChar(AppName)) <> 0 then Exit; W := CreateWindow('STATIC',PChar(AppName),100,HWND_MESSAGE,HInstance,nil); while GetMessage(M,W,0) do case M.message of WM_HOTKEY: ShellExecute(0,nil,PChar(FileNames[M.wParam]),SW_SHOWNORMAL); WM_SETHOTKEY: RegisterHotKey(W,M.wParam,M.lParam shr 16,M.lParam and $FFFF); WM_UNSETHOTKEY: UnregisterHotKey(W,M.wParam); end; end.
(要创建此程序,请选择New / VCL Forms Application,然后从项目中删除主窗体.然后选择Project / View Source并删除Application.Initialize废话.程序应如上所示.)
上面的程序监听注册新Windows热键的消息WM_SETHOTKEY,删除以前注册的热键的WM_UNSETHOTKEY,以及最终用户激活注册的热键时由Windows发送的WM_HOTKEY.前两条消息由我在此应用程序中定义.
要注册热键,请将消息WM_SETHOTKEY发送到窗口W.消息的wParam应该是要启动的程序的索引(在FileNames数组中). lParam的格式应为$MMMMKKK,其中$MMMM是修饰符(Ctrl,Alt,Shift),$KKKK是热键的虚拟键代码.要删除热键,请将带有程序索引的WM_UNSETHOTKEY消息作为wParam发送到W.
样品用法
从任何应用程序,您都可以(假设Project1.exe在后台运行)
const WM_SETHOTKEY = WM_APP + 1; WM_UNSETHOTKEY = WM_APP + 2; const MODIFIER_ALT = MOD_ALT shl 16; MODIFIER_CTRL = MOD_CONTROL shl 16; MODIFIER_SHIFT = MOD_SHIFT shl 16; procedure TForm1.RegisterHotkeys; var w: HWND; begin w := FindWindow('STATIC','Rejbrand Hot Key Listener'); PostMessage(w,WM_UNSETHOTKEY,MODIFIER_CTRL + MODIFIER_ALT + ord('N')); PostMessage(w,WM_SETHOTKEY,1,MODIFIER_CTRL + MODIFIER_ALT + ord('P')); end;
现在,即使您关闭此新程序,notepad.exe和pbrush.exe也将分别在Ctrl Alt N和Ctrl Alt P上启动.
还有一些讨论
注意,编译时,Project1.exe只有20 kB小!对于Delphi中的应用程序来说这很小!
PostMessage(w,N,0);
其中N,在这个例子中,对于记事本是= 0而对于pbrush是= 1.
要退出project1.exe,WM_QUIT,0);
但是,当然,如果退出project1.exe,Windows将取消注册所有热键.
你可能想做
procedure TForm1.RegisterHotkeys; var w: HWND; begin w := FindWindow('STATIC','Rejbrand Hot Key Listener'); if w = 0 then MessageBox('Error: Rejbrand Hot Key Listener not running!'); PostMessage(w,MODIFIER_CTRL + MODIFIER_ALT + ord('P')); end;
如果找不到窗口,甚至可以启动project1.exe.