Uunjiang第一版
26667c62创建于 2 天前历史提交
unit uuHook;

interface

uses
  //Forms,
  Menus, Classes, Messages, Dialogs, Windows, SysUtils;

type
  TuuKeyFun = (uukfCtrl, uukfShift, uukfAlt, uukfWin, uukfPrev, uukfTrans);

  TuuKeyFunSet = set of TuuKeyFun;//功能键的组合
  

function setKeyHook: Boolean;//uu,设置钩子

function unSetKeyHook: Boolean;//uu,取消钩子

var
  uuHostWndHook: THandle = 0; //uu,记录钩子句柄

implementation

uses uuAddIn;

function shortcutKeyPress(Key: wparam; lparam: lparam): Boolean;

  function funKeyPress(funKeyState: TuuKeyFunSet): Boolean;
  begin
    Result := False;
    if (uukfPrev in funKeyState) then //key原来不是按下的
      if ((LongWord(lparam) and $40000000) shr 30) <> 0 then
        Exit;
    if (uukfTrans in funKeyState) then //key现在是按下的
      if ((LongWord(lparam) and $80000000) shr 31) <> 0 then
        Exit;
    if (uukfCtrl in funKeyState) then//uu,Ctrl键按下
      if ((GetKeyState(VK_CONTROL) and $0100) <> $0100) then
        Exit;
    if (uukfShift in funKeyState) then//uu,Shift键按下
      if ((GetKeyState(VK_SHIFT) and $0100) <> $0100) then
        Exit;
    if (uukfAlt in funKeyState) then//uu,alt键按下
      if ((GetKeyState(VK_MENU) and $0100) <> $0100) then
        Exit;
    if (uukfWin in funKeyState) then//uu,Win键按下
      if ((GetKeyState(VK_LWIN) and $0100) <> $0100) and ((GetKeyState(VK_RWIN)
        and $0100) <> $0100) then
        Exit;
    Result := True; //uu,满足funKeyState的要求。
  end;

var
  KeyNo: Word; //按键 a-z
  KeyMod: TuuKeyFunSet; //控制键
begin
  Result := False;

  //快捷键是 ctrl + J
  KeyNo := 74; //J
  KeyMod := [uukfCtrl, uukfPrev, uukfTrans]; //ctrl 第一次按下时

  //按下快捷键的时候,显示窗体
  if Key = KeyNo then // J 按下
    if funKeyPress(KeyMod) then// ctrl 按下
    begin
      if WordApp.Documents.Count >0 then
        wordApp.Selection.InsertAfter('快捷键触发了');
      Result := True; // 处理了,不会继续传递按键
    end;
end;


{对于键盘钩子WH_KEYBOARD来说:
wParam,按键的虚拟代码。VK_xxx。
lParam,结构。
0~15,按键的重复次数。
16~23,按键的扫描代码。
24,按键是否为扩展键(F1~F12,小键盘数字键等),1表示是扩展键。
25~28,未定义。
29,Alt按下状态。1为按下。
30,按键的原先状态,1表示消息发送前按键原来是按下的。
31,按键当前动作,0表示按下,1表示释放。}
function KeyboardProc(code: Integer; wparam: wparam; lparam: lparam): lREsult; stdcall;
begin
  Result := 0;

  if code < 0 then
    // 小于零,继续传递
    Result := CallNextHookEx(uuHostWndHook, code, wparam, lparam)
  else
  begin

    // 大于等于零,看是否是需要的快捷键,如果是不继续传递
    if (code = HC_ACTION) and (wparam <> 0) and (lparam <> 0) then
    begin
      if shortcutKeyPress(wparam, lparam) then
      begin
        Result := 1;
        Exit;
      end;
    end;

    // 继续传递
    Result := CallNextHookEx(uuHostWndHook, code, wparam, lparam);
  end;
end;

function setKeyHook: Boolean;
begin
//安装钩子
  uuHostWndHook := SetWindowsHookEx(WH_KEYBOARD, @KeyboardProc, HInstance,
    GetCurrentThreadID);
  Result := uuHostWndHook <> 0;
end;

function unSetKeyHook: Boolean;
begin
//卸载钩子
  Result := UnhookWindowsHookEx(uuHostWndHook);
end;

end.