之前对hook也不是很了解,在网上搜了一圈,都是hook全局鼠标的,自己试验,全局也hook成功了,在对窗口hook时,怎么都不成功·····
再搜,了解到全局hook,不需要把代码放到线程内执行,对窗口hook,是把自己的代码放到窗口的线程内执行,所以,需要用C++写成DLL···
放代码:
#include "stdafx.h"
#include <windows.h>
#include <string>
#include <iostream>
//-------------------------------------------------------------
// global variables (unshared!)
//
HHOOK g_hHook = 0;
//-------------------------------------------------------------
// HookProc
// Notice:
// - executed by the instance of "HookInjEx.dll" mapped into "explorer.exe";
//
// When called from InjectDll:
// - sublasses the start button;
// - removes the hook, but the DLL stays in the remote process
// though, because we increased its reference count via LoadLibray
// (this way we disturb the target process as litle as possible);
//
// When called from UnmapDll:
// - restores the old window procedure for the start button;
// - reduces the reference count of the DLL (via FreeLibrary);
// - removes the hook, so the DLL is unmapped;
//
// Also note, that the DLL isn't unmapped immediately after the
// call to UnhookWindowsHookEx, but in the near future
// (right after finishing with the current message).
// Actually it's obvious why: windows can NOT unmap the
// DLL in the middle of processing a meesage, because the code
// in the hook procedure is still required.
// That's why we can change the order LoadLibrary/FreeLibrary &
// UnhookWindowsHookEx are called.
//
// FreeLibrary, in contrast, unmapps the DLL imeditaley if the
// reference count reaches zero.
//
#define pCW ((CWPSTRUCT*)lParam)
LRESULT HookProc(
int code, // hook code
WPARAM wParam, // virtual-key code
LPARAM lParam // keystroke-message information
)
{
return 1;
return ::CallNextHookEx(g_hHook, code, wParam, lParam);
}
//-------------------------------------------------------------
// InjectDll
// Notice:
// - injects "HookInjEx.dll" into "explorer.exe" (via SetWindowsHookEx);
// - subclasses the START button (see HookProc for more details);
//
// Parameters: - hWnd = START button handle
//
// Return value: 1 - success;
// 0 - failure;
//
extern "C" __declspec(dllexport) int InjectDll(char *str)
{
HINSTANCE hDll = ::GetModuleHandle("Win32Project2.dll"); //获取dll的句柄
HWND g_hWnd = FindWindow(NULL, str); //查找窗口
if (g_hWnd > 0)
{
g_hHook = SetWindowsHookEx(WH_MOUSE, (HOOKPROC)HookProc,
hDll, GetWindowThreadProcessId(g_hWnd, NULL));
if (g_hHook == NULL) //失败
{
return 0;
}
}
else //未找到窗口
{
return 0;
}
return 1;
}
//-------------------------------------------------------------
// UnmapDll
// Notice:
// - restores the old window procedure for the START button;
// - unmapps the DLL from the remote process
// (see HookProc for more details);
//
// Return value: 1 - success;
// 0 - failure;
//
extern "C" __declspec(dllexport) int UnmapDll()
{
if (UnhookWindowsHookEx(g_hHook))
{
return 1;
}
else
{
return 0;
}
}
C#导入调用即可