十年前碰过MFC,现在捡起来玩玩,忽然觉得都忘了,碰巧最近一个项目需要,所以贴出来一段demo。
自定义消息
BEGIN_MESSAGE_MAP(CMFCApplication1Dlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDOK, &CMFCApplication1Dlg::OnBnClickedOk)
ON_MESSAGE(WM_UPDATELABEL, onUpdateLabel)
END_MESSAGE_MAP()
Hook回调定义,传递消息的时候要注意HWnd和传的结构一定是要new出来,接收消息时释放。
HHOOK glHook = NULL;
LRESULT CALLBACK MouseProc(int nCode, WPARAM wparam, LPARAM lparam)
{
if (glWnd && IsWindow(glWnd))
{
PMOUSEHOOKSTRUCT mh = (PMOUSEHOOKSTRUCT)lparam;
POINT* newPt = new POINT;
newPt->x = mh->pt.x;
newPt->y = mh->pt.y;
::PostMessage(glWnd, WM_UPDATELABEL, 0, (LPARAM)newPt);
}
return CallNextHookEx(glHook, nCode, wparam, lparam);
}
自定义消息处理函数
LRESULT CMFCApplication1Dlg::onUpdateLabel(WPARAM wParam, LPARAM lParam)
{
POINT* mh = (POINT*)lParam;
if (mh) {
CString a;
a.Format(_T("pt2=> x:%d,y:%d\n"), mh->x, mh->y);
GetDlgItem(IDC_STATIC2)->SetWindowText(a);
// 将传过来的数据释放掉
delete mh;
mh = NULL;
}
return 0;
}
注册钩子,在初始化函数中注册全局钩子
// TODO: 在此添加额外的初始化代码
glWnd = this->GetSafeHwnd();
HINSTANCE instance = NULL;
instance = GetModuleHandle(NULL);
printf("The instance is :%p", instance);
glHook = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, instance, 0);
因为demo是个基于对话框的,所以在OnCancel中处理下释放钩子的过程
void CMFCApplication1Dlg::OnCancel()
{
OutputDebugString("Release the mouse hook");
if (glHook) {
UnhookWindowsHookEx(glHook);
}
CDialog::OnCancel();
}
下面是置前窗口和模拟点击
BOOL focusWnd(HWND targetWnd)
{
BOOL validWindow = FALSE;
if (IsWindow(targetWnd)) {
::SetForegroundWindow(targetWnd);
validWindow = TRUE;
}
return validWindow;
}
void simulateClick(POINT pt)
{
SetCursorPos(pt.x, pt.y);
Sleep(100);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);//鼠标down事件
Sleep(100);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//鼠标up事件
}
哦了,钩子很强大