本文详细描述了如何在C++中处理窗口消息,特别是鼠标右键点击事件(WM_RBUTTONDOWN),包括创建右键菜单、获取鼠标位置并显示菜单的过程。还展示了窗口的创建和消息循环机制。
//头文件
static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
HWND m_hwnd;
static CEchoCAM* m_pEcView;
//源文件
CEchoCAM* CEchoCAM::m_pEcView = NULL;
LRESULT CALLBACK CEchoCAM::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (m_pEcView == NULL)
{
return DefWindowProc(hwnd, message, wParam, lParam);
}
switch (message)
{
case WM_CREATE:
return m_pEcView->OnCreate(wParam, lParam);
case WM_DESTROY:
return 0;
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
return m_pEcView->OnPaint(wParam, lParam);
case WM_SIZE:
m_pEcView->OnSize(wParam, lParam);
break;
case WM_MOUSEMOVE:
return m_pEcView->OnMouseMove(wParam, lParam);
case WM_MOUSEWHEEL:
case WM_MOUSEHWHEEL:
return m_pEcView->OnMouseWheel(wParam, lParam);
case WM_MOUSELEAVE:
return m_pEcView->OnMouseLeave(wParam, lParam);
case WM_MOUSEHOVER:
return m_pEcView->OnMouseHover(wParam, lParam);
case WM_LBUTTONDBLCLK:
return m_pEcView->OnLButtonDBClick(wParam, lParam);
case WM_LBUTTONDOWN:
return m_pEcView->OnLButtonDown(wParam, lParam);
case WM_LBUTTONUP:
return m_pEcView->OnLButtonUp(wParam, lParam);
case WM_KEYDOWN:
return m_pEcView->OnKeyDown(wParam, lParam);
case WM_KEYUP:
return m_pEcView->OnKeyUp(wParam, lParam);
case WM_RBUTTONDOWN:
return m_pEcView->OnRButtonDown(wParam, lParam);
case WM_RBUTTONUP:
return m_pEcView->OnRButtonUp(wParam, lParam);
case WM_TIMER:
m_pEcView->OnTimer((UINT)wParam);
break;
}
return ::DefWindowProc(hwnd, message, wParam, lParam);
}
// 假设有一个名为 hwnd 的窗口句柄
// 在窗口消息处理函数中处理鼠标右键点击事件
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_RBUTTONDOWN: // 鼠标右键按下事件
// 创建右键菜单
HMENU hPopupMenu = CreatePopupMenu();
AppendMenu(hPopupMenu, MF_STRING, 1, L"修改起刀点"); // 添加菜单项
// 获取鼠标位置
POINT pt;
GetCursorPos(&pt);
// 显示右键菜单
TrackPopupMenu(hPopupMenu, TPM_LEFTALIGN | TPM_TOPALIGN, pt.x, pt.y, 0, hwnd, NULL);
DestroyMenu(hPopupMenu); // 销毁菜单
break;
// 其他消息处理
}
// 其他消息处理
}
// 在窗口的创建过程中注册窗口类
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// 窗口类注册等操作
// 创建窗口
HWND hwnd = CreateWindowEx(0, L"ClassName", L"Window Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, hInstance, NULL);
// 显示窗口
ShowWindow(hwnd, nCmdShow);
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}