如何在使用CreateProcess创建的进程上安装挂钩

How to install a hook on a process created with CreateProcess?

本文关键字:进程 安装 创建 CreateProcess      更新时间:2023-10-16

以下是我尝试过的:

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++,但安装挂钩失败,GetLastError返回以下错误:The parameter is incorrect.。我不知道哪个参数不正确。但是,当我关闭Notepad++时,程序会正常完成。

由于我在主程序中启动进程,并且钩子回调也在主程序内,因此我应该能够在不进行任何dll注入的情况下安装钩子。

我已经好几年没有接触过c++了,我也从来没有参与过系统开发,所以我做这件事的方式可能是错误的,所以你能向我解释一下我的错误在哪里吗?

编辑:你们都在告诉我,我需要注入一个dll来挂接一个特定的进程,但这是来自SetWindowsHookEx的windows文档中关于hMod参数(第三个参数(:

DLL的句柄,该句柄包含lpfn参数。如果dwThreadId参数指定由当前进程创建的线程并且如果钩子过程在与当前过程。

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

在评估输入的目的地之前,执行低级挂钩。正如SetWindowsHookEx文档中所解释的那样,这就是为什么低级别钩子需要是全局的原因。不能为dwThreadId参数传递非零值。