1

Hello I'm having following code:

var
  KeyHook: HHOOK;

function KeyHookProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
type
  PKBDLLHOOKSTRUCT = ^TKBDLLHOOKSTRUCT;
  TKBDLLHOOKSTRUCT = packed record
    vkCode: DWORD;
    scanCode: DWORD;
    flags: DWORD;
    time: DWORD;
    dwExtraInfo: DWORD;
  end;
const
  LLKHF_ALTDOWN = $20;
var
  pkbhs: PKBDLLHOOKSTRUCT;
begin
  pkbhs := PKBDLLHOOKSTRUCT(lParam);
  if nCode = HC_ACTION then
  begin
    if (pkbhs^.vkCode = VK_ESCAPE) and WordBool(GetAsyncKeyState(VK_CONTROL) and $8000) then
    begin
      Result := 1;
      Exit;
    end;
  end;
  Result := CallNextHookEx(KeyHook, nCode, wParam, lParam);
end;

initialization
  KeyHook := SetWindowsHookEx(WH_KEYBOARD_LL, @KeyHookProc, 0{HInstance}, 0);
  if KeyHook = 0 then
    RaiseLastOSError;

and this good works good when I start it as process.

But when I try to put it to work under service it doesn't work.

Doesn't work = Doesn't detect key strokes.

What I'm doing wrong?

Thanks!

Ivan Mark
  • 463
  • 1
  • 5
  • 17
  • You should edit your question to remove the part that shouldn't be there. You can do so if you're signed in with the same account that posted the question; just click the `edit` link right below the question. You should also explain what "it doesn't work" means, because without more info we can't possibly help. "it doesn't work" can mean anything from "It raises an exception" to "nothing happens" to "my computer explodes". Being more specific improves the chances of your getting an answer. :) – Ken White Jan 27 '12 at 21:35
  • It seems you are trying something impossible: http://stackoverflow.com/questions/5815424/global-keyboard-hook-from-windows-service – whosrdaddy Jan 28 '12 at 16:22

1 Answers1

2

Under Vista and up, services run in an isolated session, session 0. The keyboard is associated with the desktop of the interactive user which lives inside a different session. So your service is simply isolated from the keyboard. You will need your process to run in desktop of the interactive user.

If you are running on XP the "Allow service to interact with desktop" option may allow your hook to take effect in the context of the service. Still, that approach is not recommended.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490