c++ - 如何在使用 CreateProcess 创建的进程上安装 Hook ?

标签 c++ windows winapi hook

这是我尝试过的:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
  cout << "Starting Notepad++..." << endl;
  STARTUPINFO startupInfo;
  PROCESS_INFORMATION processInformation;

  // set the size of the structures
  ZeroMemory(&startupInfo, sizeof(startupInfo));
  startupInfo.cb = sizeof(startupInfo);
  ZeroMemory(&processInformation, sizeof(processInformation));

  char commandLine[] = "C:\\Program Files\\Notepad++\\Notepad++.exe";

  // start the program up
  BOOL res = CreateProcess(NULL,   // the path
    commandLine,        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    NULL,           // Use parent's starting directory
    &startupInfo,            // Pointer to STARTUPINFO structure
    &processInformation             // Pointer to PROCESS_INFORMATION structure (removed extra parentheses)
    );

  if (res) {
    if (!(mouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookCallback, NULL, processInformation.dwThreadId))) {
        cout << "Failed to install mouse hook :" << endl << getLastErrorAsString() << endl;
    }

    WaitForSingleObject( processInformation.hProcess, INFINITE );
    CloseHandle( processInformation.hProcess );
    CloseHandle( processInformation.hThread );
  } else {
    cout << "Failed to start Notepad++" << endl;
  }
  return 0;
}

成功启动 Notepad++,但未能安装 Hook ,GetLastError 返回以下错误:参数不正确。。我不知道哪个参数不正确。但是,当我关闭 Notepad++ 时程序正常完成。

由于我是在主程序中启动进程,而且钩子(Hook)回调也在主程序中,所以我应该可以在不进行任何dll注入(inject)的情况下安装一个钩子(Hook)。

我好多年没接触过c++了,也没有接触过系统开发,所以我做的方法可能有误,你能告诉我我的错误在哪里吗?

编辑: 你们都告诉我我需要注入(inject)一个 dll 来 Hook 特定进程,但这是来自 SetWindowsHookEx 的 Windows 文档中关于 hMod 参数(第 3 个参数)的信息:

A handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.

我的线程已经由当前进程创建,我的钩子(Hook)过程在我当前进程的代码中,那么为什么当我使用非低级钩子(Hook)(WH_MOUSE)时它不起作用?

最佳答案

低级钩子(Hook)在输入的目的地被评估之前被执行。这就是低级 Hook 需要全局的原因,如 SetWindowsHookEx 的文档中所述。 .您不能为 dwThreadId 参数传递非零值。

关于c++ - 如何在使用 CreateProcess 创建的进程上安装 Hook ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51554901/

相关文章:

c++ - OpenGL 顶点从侧面被剪切

windows - 运行时更改批处理文件

Windows 'dir' 命令,按名称排序和 <something>

c++ - EnumDisplaySettings 最大模式数

c++ - 使用winapi计算按钮大小

c - BITMAPINFOHEADER biHeight 是我预期的两倍

c++ - 无法根据opencv RotatedRect教程得到相同的图像结果

c++ - 从弧度转换为度数

c++ - 调用传递给它的对象的成员方法的仿函数的部分模板特化

c# - Windows、.NET 读取鼠标光标下的文本