21xrx.com
2024-11-22 07:06:27 Friday
登录
文章检索 我的文章 写文章
C++弹出菜单制作
2023-07-06 21:00:59 深夜i     --     --
C++ 弹出菜单 制作 GUI MFC

在C++编程语言中,在GUI程序中添加弹出式菜单是一个非常常用的功能,而且也比较简单。接下来将会介绍如何在C++中制作弹出菜单。

首先,需要包含Windows.h头文件,然后定义一个函数,该函数将使用CreatePopupMenu()函数创建弹出式菜单。此函数将添加一些菜单项,使用AppendMenu()函数,并设置菜单项的ID。

接下来,在程序中需要定义一个包含WM_COMMAND消息处理程序的Widows消息循环。WM_COMMAND消息处理程序将在用户选择菜单项时被调用,并且需要检查菜单项的ID,以知道哪个菜单项被选择。

下面是一个基本的示例程序:


#include <windows.h>

HMENU hPopupMenu;

void createPopupMenu(HWND hWnd)

{

  hPopupMenu = CreatePopupMenu();

  AppendMenu(hPopupMenu, MF_STRING, 0, "File");

  AppendMenu(hPopupMenu, MF_STRING, 1, "Edit");

  AppendMenu(hPopupMenu, MF_STRING, 2, "View");

  AppendMenu(hPopupMenu, MF_STRING, 3, "Help");

}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)

{

  switch (uMsg)

  {

    case WM_CREATE:

      createPopupMenu(hWnd);

      break;

    case WM_COMMAND:

      switch (LOWORD(wParam))

      {

        case 0:

          MessageBox(hWnd, "File selected", "Menu", MB_OK);

          break;

        case 1:

          MessageBox(hWnd, "Edit selected", "Menu", MB_OK);

          break;

        case 2:

          MessageBox(hWnd, "View selected", "Menu", MB_OK);

          break;

        case 3:

          MessageBox(hWnd, "Help selected", "Menu", MB_OK);

          break;

      }

      break;

    case WM_DESTROY:

      PostQuitMessage(0);

      break;

    case WM_RBUTTONUP:

      POINT p;

      GetCursorPos(&p);

      TrackPopupMenu(hPopupMenu, TPM_RIGHTBUTTON, p.x, p.y, 0, hWnd, NULL);

      break;

    default:

      return DefWindowProc(hWnd, uMsg, wParam, lParam);

  }

  return 0;

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)

{

  WNDCLASSEX wc = {0};

  wc.cbSize = sizeof(WNDCLASSEX);

  wc.lpfnWndProc = WindowProc;

  wc.hInstance = hInstance;

  wc.lpszClassName = "MyClass";

  if (!RegisterClassEx(&wc))

    return -1;

  HWND hWnd = CreateWindowEx(0, "MyClass", "Popup Menu", WS_OVERLAPPEDWINDOW, 100, 100, 500, 500, NULL, NULL, hInstance, NULL);

  if (!hWnd)

    return -1;

  ShowWindow(hWnd, nShowCmd);

  MSG msg = {0};

  while (GetMessage(&msg, NULL, 0, 0) > 0)

  {

    TranslateMessage(&msg);

    DispatchMessage(&msg);

  }

  return msg.wParam;

}

在这个例子中,我们创建一个包含四个菜单项的弹出式菜单,在用户单击右键时弹出。当用户选择任何一个菜单项时,会弹出相应的消息框。有关CreatePopupMenu()和AppendMenu()函数的详细文档,请参阅MSDN文档。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复