15,473
社区成员




class CHostDlg : public CDialog
{
// Construction
public:
CHostDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CHostDlg)
enum { IDD = IDD_HOST_DIALOG };
CEdit m_EdtWnd;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CHostDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CHostDlg)
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnBtnStart();
afx_msg void OnBtnStop();
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
//}}AFX_MSG
afx_msg LRESULT OnHookMsg(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
void CHostDlg::OnBtnStart()
{
// TODO: Add your control notification handler code here
this->SetCapture();
m_EdtWnd.SetWindowText(_T("单击任意窗体"));
}
void CHostDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
::ReleaseCapture();
POINT pt;
::GetCursorPos(&pt);
HWND hWnd = ::WindowFromPoint(pt);
TCHAR szCaption[128];
::GetWindowText(hWnd, szCaption, 127);
DWORD dwThreadId = ::GetWindowThreadProcessId(hWnd, NULL);
if (dwThreadId != 0)
{
if (SetHook(this->m_hWnd, dwThreadId))
StrCat(szCaption, _T("-钩挂成功"));
else
StrCat(szCaption, _T("-钩挂失败"));
m_EdtWnd.SetWindowText(szCaption);
}
CDialog::OnLButtonUp(nFlags, point);
}
LRESULT CHostDlg::OnHookMsg(WPARAM wParam, LPARAM lParam)
{
POINT pt;
TCHAR szInfo[128];
::GetCursorPos(&pt);
wsprintf(szInfo, "鼠标位置:X:%d Y:%d", pt.x, pt.y);
m_EdtWnd.SetWindowText(szInfo);
return 0;
}
void CHostDlg::OnBtnStop()
{
// TODO: Add your control notification handler code here
UnHook();
m_EdtWnd.SetWindowText(NULL);
}
#ifdef HOOK_EXPORTS
#define HOOK_API __declspec(dllexport)
#else
#define HOOK_API __declspec(dllimport)
#endif
#define WM_HOOK WM_USER + 1
HOOK_API BOOL SetHook(HWND hWindow, DWORD dwThreadId);
HOOK_API BOOL UnHook();
#include "stdafx.h"
#include "Hook.h"
#pragma data_seg("HookShared")
HHOOK hHook = NULL;
HWND hWnd = NULL;
#pragma data_seg()
#pragma comment(linker, "/SECTION:HookShared,RWS")
HINSTANCE hMod;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
hMod = (HINSTANCE)hModule;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
LRESULT WINAPI HookProc(int code, WPARAM wParam, LPARAM lParam)
{
PMSG pMsg = (PMSG)lParam;
if (pMsg->message == WM_MOUSEMOVE)
SendMessage(hWnd, WM_HOOK, pMsg->wParam, pMsg->lParam);
return CallNextHookEx(hHook, code, wParam, lParam);
}
HOOK_API BOOL SetHook(HWND hWindow, DWORD dwThreadId)
{
hWnd = hWindow;
hHook = SetWindowsHookEx(WH_GETMESSAGE, HookProc, hMod, dwThreadId);
return hHook != NULL;
}
HOOK_API BOOL UnHook()
{
hWnd = NULL;
return UnhookWindowsHookEx(hHook);
}