How to Use CMenu to dynamically add pop-up menus and response functions in MFC

Source: Internet
Author: User

Method:
Use the CMenu class in MFC to dynamically add pop-up menus and Response Functions

Steps:

1. Declare a menu:

CMenu menu;

2. Generate a menu object:

Menu. CreatePopupMenu ();

3. Add the following content to the menu:

Menu. AppendMenu (MF_STRING, WM_CLEARHOSTS, "Clear HOSTS ");

For more information about the AppendMenu function, see MSDN. WM_CLEARHOSTS is a custom message, and the last parameter is the text of the menu. Click this menu to call the WM_CLEARHOSTS message processing function.

4. Add a bullet menu:

CMenu submenu;

Submenu. CreatePopupMenu ();

Menu. AppendMenu (MF_POPUP, (UINT_PTR) (submenu. m_hMenu), "sub ");

5. The menu disappears automatically when the focus is lost.

SetForegroundWindow ();

6. Set the menu position:

Menu. TrackPopupMenu ();

The above steps are a complete step for dynamically generating menus. When there are many dynamically generated menus and the menus are not fixed

It is difficult and unrealistic to define a message and message processing function for each menu. Now we will introduce a method to dynamically respond to dynamically generated menus.

The principle is to use the OnCommand function.

First, you must specify an ID for each dynamically generated menu.

Menu. AppendMenu (MF_STRING, ID, "yourMenuName ");

The parameter ID is a unique integer that can be specified by you. When you click this menu, the system sends a message, which takes priority.

Received by the OnCommand function. The original form of the OnCommand function is:

BOOL OnCommand (WPARAM wParam, LPARAM lParam );

If you specify the menu ID as 10001, the response function is written as follows:

BOOL OnCommand (WPARAM wParam, LPARAM lParam)

{
Int menuID = LOWORD (wParam );
If (menuID & gt; 10000)
{
// Add your own processing code
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.