A popup menu

蓬野
2023-12-01
#include <windows.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

#define IDM_FILE_NEW 1
#define IDM_FILE_OPEN 2
#define IDM_FILE_QUIT 3


int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PWSTR lpCmdLine, int nCmdShow)
{
  MSG  msg;    
  WNDCLASSW wc = {0};
  wc.lpszClassName = L"Application";
  wc.hInstance     = hInstance;
  wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
  wc.lpfnWndProc   = WndProc;
  wc.hCursor       = LoadCursor(0, IDC_ARROW);


  RegisterClassW(&wc);
  CreateWindowW(wc.lpszClassName, L"Popup Menu",
                WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                100, 100, 200, 150, 0, 0, hInstance, 0);

  while( GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }

  return (int) msg.wParam;
}

LRESULT CALLBACK WndProc( HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam )
{
  HMENU hMenu;
  POINT point;

  switch(msg)  
  {
    case WM_COMMAND:
        switch(LOWORD(wParam)) { // 在WM_COMMAND中 wParam的低字段是子窗口ID
            case IDM_FILE_NEW:
            case IDM_FILE_OPEN:
                Beep(50, 100);
                break;
            case IDM_FILE_QUIT:
                SendMessage(hwnd, WM_CLOSE, 0, 0);
                break;
        }
        break;

    case WM_RBUTTONUP:  //鼠标右键释放时产生此消息
			//lParam的低字段和高字段分别是相对于客户区左上角的x,y坐标
        point.x = LOWORD(lParam);//
        point.y = HIWORD(lParam);
        hMenu = CreatePopupMenu();//创建菜单
        ClientToScreen(hwnd, &point); //转换客户区坐标到屏幕坐标

        AppendMenuW(hMenu, MF_STRING, IDM_FILE_NEW, L"&New");
        AppendMenuW(hMenu, MF_STRING, IDM_FILE_OPEN, L"&Open");
        AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);
        AppendMenuW(hMenu, MF_STRING, IDM_FILE_QUIT, L"&Quit");
                    
        TrackPopupMenu(hMenu, TPM_RIGHTBUTTON, point.x, point.y, 0, hwnd, NULL);//在指定的x,y点生成右键菜单
        
			DestroyMenu(hMenu);//由于菜单hMenu没有附着于任何窗口,应该显性销毁.

        break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;
  }

  return DefWindowProcW(hwnd, msg, wParam, lParam);
}

 类似资料:

相关阅读

相关文章

相关问答