Windows Global Keyboard Hook - Delphi

允我心安 提交于 2019-11-28 20:56:27

You are not assigning your hMemo and hApp values early enough. You are waiting until a notification with a "previous state" flag of 1, which indicates a key has been held down for at least 1 repeat count, or is being released, whichever occurs first. Thus, hMemo and hApp are not available yet when your hook detects its first key down notification. That is why you miss characters. Try this instead:

function KeyHookFunc(Code, VirtualKey, KeyStroke: Integer): LRESULT; stdcall;
var
  KeyState1: TKeyBoardState;
  AryChar: array[0..1] of Char;
  Count: Integer;
begin
  Result := CallNextHookEx(hKeyHook, Code, VirtualKey, KeyStroke);
  if Code <> HC_ACTION then Exit;

  { a key notification had occured, prepare the HWNDs
  before checking the actual key state }
  if (hMemo = 0) or (hApp = 0) then
  begin
    if hMemFile = 0 then
    begin
      hMemFile := OpenFileMapping(FILE_MAP_WRITE, False, 'NetParentMAP');
      if hMemFile = 0 then Exit;
    end;
    if PHookRec1 = nil then
    begin
      PHookRec1 := MapViewOfFile(hMemFile, FILE_MAP_WRITE, 0, 0, 0);
      if PHookRec1 = nil then Exit;
    end;
    hMemo := PHookRec1.MemoHnd;
    hApp  := PHookRec1.AppHnd;
    if (hMemo = 0) and (hApp = 0) then Exit;
  end;

  if ((KeyStroke and (1 shl 31)) = 0) then // a key is down
  begin
    GetKeyboardState(KeyState1);
    Count := ToAscii(VirtualKey, KeyStroke, KeyState1, AryChar, 0);
    if Count = 1 then
    begin
      if hMemo <> 0 then SendMessage(hMemo, WM_CHAR, Ord(AryChar[0]), 0);
      if hApp <> 0 then PostMessage(hApp, WM_USER + 1678, Ord(AryChar[0]), 0);
    end;
  end;
end;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!