#include <windows.h>
#include <stdio.h>
#pragma data_seg ("shareddata")
HWND globalHook = NULL;
HINSTANCE g_hHINS = NULL;//共享数据
#pragma data_seg()
//#pragma comment(linker,"/section:sharedata,rws")
BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
g_hHINS = (HINSTANCE)hModule;
return TRUE;
}
extern "C" _declspec(dllexport) HHOOK LoadHook(HWND);
extern "C" _declspec(dllexport)LRESULT CALLBACK HookProc
(
int nCode,
WPARAM wParam,
LPARAM lParam
);
LRESULT CALLBACK HookProc
(
int nCode,
WPARAM wParam,
LPARAM lParam
) {
MSG *kmsg;
static int control[5] = {0,0,0,0,0};
kmsg = (MSG*)lParam;
if(kmsg->message!= WM_KEYDOWN&&kmsg->message!=WM_KEYUP)
return CallNextHookEx(NULL, nCode, wParam, lParam);
if (kmsg->message == WM_KEYDOWN) {
switch (kmsg->wParam) {
case VK_CONTROL:
// MessageBox(globalHook, "OK", "a", 0);
control[0] = 1; break;
case 'W':if (control[0] && !control[1])
{
kmsg->wParam = VK_UP;
// MessageBox(globalHook, "OK", "a", 0);
control[1] = 1;
}break;
case 'A':if (control[0] && !control[2])
{
kmsg->wParam = VK_LEFT;
control[2] = 1;
}break;
case 'S':if (control[0] && !control[3])
{
kmsg->wParam = VK_DOWN;
control[3] = 1;
} break;
case 'D':if (control[0] && !control[4])
{
kmsg->wParam = VK_RIGHT;
control[4] = 1;
} break;
}
}
else if(kmsg->message == WM_KEYUP){
switch (kmsg->wParam) {
case 'W':if (control[1])
{
kmsg->wParam = VK_UP;
control[1] = 0;
}break;
case 'A':if (control[2])
{
kmsg->wParam = VK_LEFT;
control[2] = 0;
}break;
case 'S':if (control[3])
{
kmsg->wParam = VK_DOWN;
control[3] = 0;
} break;
case 'D':if (control[4])
{
kmsg->wParam = VK_RIGHT;
control[4] = 0;
} break;
}
}
return CallNextHookEx(NULL,nCode, wParam, lParam);
}
HHOOK LoadHook(HWND hWnd){
globalHook = hWnd;
char error[100];
ZeroMemory(error, 100);
HHOOK hHook= SetWindowsHookEx(WH_GETMESSAGE, HookProc, g_hHINS, 0);
if (hHook == NULL) {
sprintf_s(error, "%d", GetLastError());
MessageBox(hWnd, error, "Hook错误", 0);
}return hHook;
}我想通过全局钩子实现把w,s,a,d转换↑↓←→,在记事本可以实现 但为什么对Visual Studio这样的编辑器没用?
------解决思路----------------------
1 是否存在权限问题。即要hook的程序是管理员,你的hook程序也要权限提升
2. 我刚刚测试了message hook 确实可以hook到vs2008 or vs2015
3. 你可以考虑低级键盘钩子hook。这样一个exe就可以了,不用dll。