我试图挂钩外部进程(Cubase)以便按顺序拦截键盘事件(特别是" ctrl + shift + s" [另存为])到SendInput(...)
使用当前日期&填充文件名文本区域时间。过了一段时间,我意识到我几乎不能理解C++
以达到理想的结果,所以我稍微调整了this code。
DLL:
#include <windows.h>
#include <stdio.h>
HINSTANCE hinst;
#pragma data_seg(".shared")
HHOOK g_hook = 0;
#pragma data_seg()
LRESULT CALLBACK HookProc(int code, WPARAM wParam, LPARAM lParam) {
printf_s("callback...\n");
if (code < 0) {
return CallNextHookEx(g_hook, code, wParam, lParam);
}
KBDLLHOOKSTRUCT kbd = *((KBDLLHOOKSTRUCT*) lParam);
if (kbd.vkCode == 0x53 && GetKeyState(VK_CONTROL) < 0 && GetKeyState(VK_SHIFT) < 0) { // 0x53 -> 's'
MessageBox(NULL, "ctrl + shift + s", "CALLBACK", MB_ICONINFORMATION);
}
return CallNextHookEx(g_hook, code, wParam, lParam);
}
extern "C" __declspec(dllexport) void install(DWORD threadID) {
if (!(g_hook = SetWindowsHookEx(WH_KEYBOARD, HookProc, hinst, threadID))) {
printf_s("failed installing hook...\n");
}
else {
printf_s("hook installed...\n");
}
}
extern "C" __declspec(dllexport) void uninstall() {
UnhookWindowsHookEx(g_hook);
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
hinst = hinstDLL;
return TRUE;
}
main.cpp中:
#include <tchar.h>
#include <Windows.h>
#define APP_PATH _T("C:\\Program Files (x86)\\Steinberg\\Cubase 5\\Cubase5.exe")
int _tmain(int argc, _TCHAR* argv[]) {
HINSTANCE hinst = LoadLibrary(_T("CuBaseHook.dll"));
if (hinst) {
typedef void (*Install)(DWORD);
typedef void (*Uninstall)();
Install install = (Install) GetProcAddress(hinst, "install");
Uninstall uninstall = (Uninstall) GetProcAddress(hinst, "uninstall");
STARTUPINFO info{ sizeof(info) };
PROCESS_INFORMATION pInfo;
if (CreateProcess(APP_PATH, "", NULL, NULL, TRUE, 0, NULL, NULL, &info, &pInfo)) {
install(pInfo.dwThreadId);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) != 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
uninstall();
}
}
return 0;
}
以上编译,但在SetWindowsHookEx(WH_KEYBOARD, HookProc, hinst, threadID)
DLL
函数的install(...)
上失败。
坦率地说,我不明白为什么。是hinstDLL
还是threadID
问题?
PS:如果有其他方法可以达到预期效果,那么请一定告诉我......