VC++ MFC Example: Display Context Menu in SDI

Updated on November 21, 2018
sirama profile image

I am a software engineer. I have been come across C++,MFC, .net technologies. I like playing video games & reading books.

1. Introduction

In this article, we will create main menu with four menu items in it. The last menu item will open a sub-menu. The menu will be displayed when the mouse is right-clicked in the client area of the window and at the location of the mouse pointer.

2. About the Example

The below screenshot shows the application sample:

MFC Popup Menu Example
MFC Popup Menu Example | Source

The Example is an SDI Application without document and view architecture support. We marked the client area with a yellow border in the below screenshot. When the mouse pointer is inside the client area of the window, MFC will display a pop-up menu.

Here, we are creating the Menu items at run-time and displaying the Pop-up Menu as shown in the above screenshot. The video given below shows default setting overridden for MFC SDI Application.

Video 1: Creating MFC SDI Application without Document View Support (No Audio)

3. Process WM_CONTEXTMENU

When the Mouse is right clicked inside the client area of the Window, the Window will get a notification message WM_CONTEXTMENU. This message will come with the Window Handle in which the Mouse is right clicked. In addition, it also contains Mouse Pointer position in Screen Coordinate where the right click happened. We will use this notification message to display the Pop-up Menu.

The video given below shows how to provide a handler for the WM_CONTEXTMENU message. We will handle this Window message in the CChildView.

Video 2: Adding Handler for the Message WM_CONTEXTMENU (No Audio)

In the video, we saw a view class which provides the handler for the WM_CONTEXTMENU message. The handler looks like below:

void CChildView::OnContextMenu(CWnd* pWnd, CPoint point)

Here, pWnd is the pointer to the window in which the user produces the right client. The second parameter called a point in this function supplies the mouse cursor location in Screen Coordinates.

4. Display Context Menu by Handling OnContextMenu

The menu is created in side the handler provided for the WM_CONTEXTMENU.

1) First We declare a CRect class to get the client window dimensions. Next, we create SubMenu and MainMenu instance of type CMenu.

void CChildView::OnContextMenu(CWnd* pWnd, CPoint point)
{
	//Sample 01: Declarations
	CRect client_rect;
	CMenu SubMenu, MainMenu;

2) After the Declarations, we get the client area of the window in client_rect structure. Then, we convert this structure into Screen Co-Ordinate which has the origin from the top left of our monitor. We do this because the point parameter given to our handler as a second argument is in Screen Co-Ordinate.

//Sample 02: Get Mouse Click position and 
//convert it to the Screen Co-ordinate
GetClientRect(&client_rect);
ClientToScreen(&client_rect);

3) We will display the pop-up context menu when the mouse is right clicked only inside the client area of the window. Therefore, we should check the mouse click position lies inside the client rectangle dimension. Note that as we get the mouse position in screen co-ordinate, we converted the rectangle dimension of the client_rect into Screen Co-Ordinate. We need this for performing the right-clicked location is inside the client area of the SDI application window. We use the function PtInRect to achieve this.

//Sample 03: Check the mouse pointer position is 
//inside the client area
if( client_rect.PtInRect(point))
{

4) After the point is inside the rectangle test, the Sub-Menu for the Context Menu is created by calling the CreatePopupMenu function of the CMenu object. Then, the Menu Items are added to it using the AppendMenu function call. The first parameter passed to it as MF_STRING denotes that we are adding a String Menu Item. The second parameter is ID value which we gave while creating Menu Item. We will use later this Id when we need to process Command Message (Not covered in this article). The last parameter is Display String of the Menu Item.

Once the Sub-Menu is created, we create the Main Menu. We create this Menu the same way the Sub-Menu was created. However, the last item on the Main Menu is a linked to the Sub-Menu which we already created. Note, we added the Sub-Menu to this Main Menu by sending the MF_POPUP as the first parameter to the function call AppendMenu. This will show the AppendMenu function that unlike the normal Menu Item it should create the Cascading Menu for the Menu Item named "Line Thickness". Below is the code:

//Sample 04: Create the sub Menu First
SubMenu.CreatePopupMenu();
SubMenu.AppendMenu(MF_STRING, 4001, _T("1"));
SubMenu.AppendMenu(MF_STRING, 4002, _T("2"));
SubMenu.AppendMenu(MF_STRING, 4003, _T("4"));
SubMenu.AppendMenu(MF_STRING, 4004, _T("8"));

//Sample 05:Create the Main Menu
MainMenu.CreatePopupMenu();
MainMenu.AppendMenu(MF_STRING, 4005, _T("Line"));
MainMenu.AppendMenu(MF_STRING, 4006, _T("Circle"));
MainMenu.AppendMenu(MF_STRING, 4007, _T("Polygon"));
MainMenu.AppendMenu(MF_POPUP, 
	(UINT)SubMenu.GetSafeHmenu(), 
	_T("Line Thickness"));

5) Finally, we call TrackPopupMenu to display the Menu which we created earlier. The first parameter TPM_LEFTALIGN tells that the displayed pop-up menu should be left aligned with the cursor location. The x, y position tells where we want to display the MainMenu as a Pop-Up Menu.

//Sample 06: Display the Popup Menu
MainMenu.TrackPopupMenu(TPM_LEFTALIGN, 
point.x, point.y, this);

Video 3: Display of Popup Menu in the SDI Application (No Audio)

Source Code: Download

Questions & Answers

    © 2018 sirama

    Comments

      0 of 8192 characters used
      Post Comment

      No comments yet.

      working

      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

      Show Details
      Necessary
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
      Features
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Marketing
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Statistics
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
      ClickscoThis is a data management platform studying reader behavior (Privacy Policy)