VC to achieve the dynamic menu creation method

  • 2020-04-02 02:25:47
  • OfStack

This paper briefly describes the method of dynamically creating the system tray menu when the program does not support MFC and the CMenu is not available. Since the menu items are uncertain, you need to use the SDK to create a dynamic pop-up menu.

The main implementation code is as follows:

//------------------ code begin ----------------

//Variables defined in the class:
//The corresponding menu item id when double-clicking the tray icon.
UINT m_nDClickMenuItemId;
//Popup menu handle.
m_hMenu m_hMenu;

//Create right-click menu items dynamically.
///@param item_text menu item text string, separated by commas.
///@param dbclick_id double-click the menu item id corresponding to the tray icon.
//Call example:
//Create_menu (" show/hide, exit ", 40001);
BOOL CTrayIconMenu::create_menu(char* item_text, unsigned int dbclick_id)
  m_nDClickMenuItemId = dbclick_id;

  //Dynamically create pop-up menus
  m_hMenu = ::CreatePopupMenu();
  if (m_hMenu == NULL) {
    return 0;

  int i=0;
  int msgid=40001;  //Message id for the first menu item.
  BOOL ret = 0;
  char * pText = ::strtok(item_text, ",");
  while( pText != NULL )  {
    ret = ::AppendMenu(m_hMenu, MF_ENABLED | MF_STRING, msgid + i, pText);
    pText = ::strtok( NULL, "," );

  return 1;

/// response message displays menu.
LRESULT CTrayIconMenu::on_msg(WPARAM wid, LPARAM event)
  //Some other processing code...

  POINT mouse;

  //HWnd is the application's main window handle.
  if (event == WM_RBUTTONUP)  {
    ::TrackPopupMenu(m_hMenu, 0, mouse.x, mouse.y, 0, hWnd, NULL);
  return 1;

//------------------ code end ----------------

Related articles: