Click here to Skip to main content
15,892,161 members
Articles / Desktop Programming / MFC

Reduced Context Menus

Rate me:
Please Sign up or sign in to vote.
3.78/5 (5 votes)
5 Nov 20021 min read 81.1K   2.3K   32  
This code provides a simple way to remove disabled items from a context menu.
/////////////////////////////////////////////////////////////////////////////
//	Source file part of Starfix MProc application
//	Copyright Fugro Survey 2002
//	Author:	Stephen Fewings 
//	Date:	October-2002
//
// ContextMenu.cpp : implementation of custom context menu
//
/////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ContextMenu.h"
#include "ReducedMenu.h"



BOOL CReducedMenu::TrackPopupMenu( UINT nFlags, int x, int y, CWnd* pWnd, LPCRECT lpRect )
{
	CullDisabledItems(this);
	return CMenu::TrackPopupMenu( nFlags,x,y,pWnd,lpRect);
}

void CReducedMenu::CullDisabledItems(CMenu* pMenu)
{
	CEnabledCmdUI state;
	UINT n;

	// go through each menu item and remove disabled items
	for(n =0; n < pMenu->GetMenuItemCount(); n++)
	{
		state.m_nID = pMenu->GetMenuItemID( n );

		// menu separator or invalid cmd - ignore it
		if (state.m_nID == 0) 
			continue; 

		if (state.m_nID == (UINT)-1)
		{
			// possibly a popup menu, route to child menu if so
			CMenu* pSub=pMenu->GetSubMenu(n);
			if(pSub) 
				CullDisabledItems(pSub);
		}
		else 
		{
			// normal menu item, Remove it if the command is disabled
			AfxGetMainWnd()->OnCmdMsg(state.m_nID, CN_UPDATE_COMMAND_UI, &state, NULL);
			if( !state.m_bEnabled )
			{
				pMenu->DeleteMenu( n--, MF_BYPOSITION );
			}
		}
	}

	// now remove spare separators
	for (n =0; n < pMenu->GetMenuItemCount(); n++)
	{
		UINT nID = pMenu->GetMenuItemID( n );

		// if separator is first or last item in menu- remove it
		if (nID == 0 && (n == 0 || n == pMenu->GetMenuItemCount()-1) ) 
		{
			pMenu->DeleteMenu( n--, MF_BYPOSITION );
		}

		// if two adjacent separators, remove one
		if (n > 0 && nID == 0 && pMenu->GetMenuItemID( n-1 ) == 0 )
		{
			pMenu->DeleteMenu( n--, MF_BYPOSITION );			
		}
	}		
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


Written By
Web Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions