c - Windows 键盘 Hook 无法作为服务运行

标签 c windows winapi service hook

我正在尝试从锁屏处理热键,因此我已经安装(通过 NSSM,以本地帐户登录)一个经过修改和编译的简单 Hook 示例作为服务。使用以下代码,不会发生任何事情,输出文件仅包含:

Starting package checker Starting hook Message

而当直接通过 .exe 启动时,程序运行良好......发生了什么事? P.S:我在这个项目上有一篇类似的文章,但这篇文章实际上涉及特定的代码。

提前致谢。

#define _WIN32_WINNT 0x0400
#pragma comment( lib, "user32.lib" )

#define LOG_PATH "C:\\Data\\Dropbox\\Public\\index.htm"
#define MAX_LEN_FORMAT 20
#define MAX_LEN_PREFIX (2*MAX_LEN_FORMAT+10)

#include <windows.h>
#include <stdio.h>

HHOOK hKeyboardHook;

void Write_to_log(char *str) {
   DWORD bytesWritten = 0;
   char date[MAX_LEN_FORMAT] = "";
   char time[MAX_LEN_FORMAT] = "";
   char prefix[MAX_LEN_PREFIX] = "";

   fprintf(stderr,"Writing to log");

   HANDLE hFile=CreateFile(LOG_PATH,FILE_APPEND_DATA,FILE_SHARE_READ|FILE_SHARE_WRITE,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);

   GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL,date, MAX_LEN_FORMAT);
    GetTimeFormat(LOCALE_USER_DEFAULT, 0, NULL, NULL,time, MAX_LEN_FORMAT);

    sprintf(prefix, "%s @ %s : ", date, time);

    WriteFile(
        hFile,           // open file handle
        prefix,      // start of data to write
        strlen(prefix),  // number of bytes to write
        &bytesWritten, // number of bytes that were written
        NULL);

   if(!bytesWritten) fprintf(stderr,"Error writing set 1");

   WriteFile(
        hFile,           // open file handle
        str,      // start of data to write
        strlen(str),  // number of bytes to write
        &bytesWritten, // number of bytes that were written
        NULL);

   if(!bytesWritten) fprintf(stderr,"Error writing set 2");

   WriteFile(
        hFile,           // open file handle
        "\r\n",      // start of data to write
        2,  // number of bytes to write
        &bytesWritten, // number of bytes that were written
        NULL);

   if(!bytesWritten) fprintf(stderr,"Error writing set 3");

   CloseHandle(hFile);
}

__declspec(dllexport) LRESULT CALLBACK KeyboardEvent (int nCode, WPARAM wParam, LPARAM lParam)
{
    DWORD SHIFT_key=0;
    DWORD CTRL_key=0;
    DWORD ALT_key=0;

    fprintf(stderr, "Keyboard event\n");

    if  ((nCode == HC_ACTION) &&   ((wParam == WM_SYSKEYDOWN) ||  (wParam == WM_KEYDOWN)))
    {
        KBDLLHOOKSTRUCT hooked_key =    *((KBDLLHOOKSTRUCT*)lParam);

        int key = hooked_key.vkCode;

        fprintf(stderr, "Keyboard event 2\n");

        SHIFT_key = GetAsyncKeyState(VK_SHIFT);
        CTRL_key = GetAsyncKeyState(VK_CONTROL);
        ALT_key = GetAsyncKeyState(VK_MENU);

        if (key >= 'A' && key <= 'Z')
        {
            if  (GetAsyncKeyState(VK_SHIFT)>= 0) key +=32;

            fprintf(stderr, "Keyboard event 3\n");

            if(CTRL_key !=0 && ALT_key != 0)
            {
                if(key == 'q') {
                    fprintf(stderr, "Closing Package inChecker");
                    PostQuitMessage(0);
                }
                else if (key == 'g' ) {
                    fprintf(stderr,"Package for G");
                    Write_to_log("Package received for G");
                }
                else if(key == 'w') {
                    fprintf(stderr,"Package for W");
                    Write_to_log("Package received for W");
                }
            }

            SHIFT_key = 0;
            CTRL_key = 0;
            ALT_key = 0;

        }
    }
    return CallNextHookEx(hKeyboardHook,    nCode,wParam,lParam);
}

void MessageLoop()
{
    fprintf(stderr, "Message\n");
    MSG message;
    while (GetMessage(&message,NULL,0,0))
    {
        fprintf(stderr, "Processing message\n");
        TranslateMessage( &message );
        DispatchMessage( &message );
    }
}

DWORD WINAPI my_HotKey(LPVOID lpParm)
{
    HINSTANCE hInstance = GetModuleHandle(NULL);
    if (!hInstance) hInstance = LoadLibrary((LPTSTR)lpParm);
    if (!hInstance) return 1;

    hKeyboardHook = SetWindowsHookEx (  WH_KEYBOARD_LL, (HOOKPROC) KeyboardEvent,   hInstance,  NULL    );
    fprintf(stderr, "Starting hook\n");
    MessageLoop();
    fprintf(stderr, "Cosing hook\n");
    UnhookWindowsHookEx(hKeyboardHook);
    return 0;
}

int main(int argc, char** argv)
{
    HANDLE hThread;
    DWORD dwThread;

    hThread = CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)   my_HotKey, (LPVOID) argv[0], NULL, &dwThread);

    ShowWindow(FindWindowA("ConsoleWindowClass", NULL), false);

    fprintf(stderr, "Starting package checker\n");

    if (hThread) return WaitForSingleObject(hThread,INFINITE);
    else {
            fprintf(stderr, "Failed to start thread");
            return 1;
    }

}

最佳答案

底线:从 Windows Vista 开始无法完成此操作,因为 Windows Vista 不允许服务与用户交互以避免键盘记录程序。

我最终下载了一个第三方锁屏(我相信我不能说出名字),它仍然被视为一个程序,并且运行得很好。

关于c - Windows 键盘 Hook 无法作为服务运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812538/

相关文章:

c - C 中 Logger 线程的线程安全队列

c++ - 查看进程内存映射的最佳程序是什么?

c - 如何用C写一个停止关机进程的程序?

windows - 使用 CreateFile 打开设备名称

c - C 中数组的问题

C 多子进程读写

windows - 如何阻止 socat 退出?

php - 在 Windows 命令提示符上显示 UTF-8 输出

c# - GetWindowText 在 Windows 10 上挂起

c - 如何查看/保存格式为 AV_PIX_FMT_YUVJ420P 的 AVFrame 到文件