How to draw a custom menu on MFC SDI dynamically - c++

I am trying to draw a custom popup menu on MFC single-document interface (SDI) project.
From here, I found The framework calls this member function for the owner of an owner-draw button control, combo-box control, list-box control, or menu when a visual aspect of the control or menu has changed.
So I added the handle OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct) and added some code inside this function, but I found that this callback didn't be called by the framework when I right click on the view, like this:
How to make a popup menu dynamically?
Here is how I get my pop up menu:
void Cdynamic_menu_sdiView::OnContextMenu(CWnd* /* pWnd */, CPoint point)
{
if (IDR_MY_MENU == 0)
return;
CMenu dynamicMenu, proxyMenu;
if (dynamicMenu.GetSafeHmenu())
dynamicMenu.DestroyMenu();
// Create a new popup menu.
if (dynamicMenu.CreatePopupMenu() == FALSE)
return;
if (proxyMenu.LoadMenu(IDR_MY_MENU) == FALSE)
return;
int nSubMenu = 1;
CMenu* pProxyMenu = proxyMenu.GetSubMenu(nSubMenu);
build_dynamic_menu(m_map_menu_element_2, pProxyMenu, dynamicMenu, CString(""));
//m_menu_on_draw = &dynamicMenu; // link up the dynamic menu to the on draw menu, so that we can print it on the screen
CPoint ptCurPos; // current cursor position
GetCursorPos(&ptCurPos);
dynamicMenu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, ptCurPos.x, ptCurPos.y, AfxGetMainWnd(), NULL);
}
Inside the function build_dynamic_menu(), it is a depth first search function, I do InsertMenu(i, MF_BYPOSITION | MF_POPUP | MF_OWNERDRAW, uSubMenuID, strLabel); so that I can change the text of the popup menu dynamically.
Since it is too long to put the function here, I only state the idea.
I also want to change the text color and background color dynamically, so I am trying to find a way to draw the menu by code.
Where should I start? Is owner drawn menus approach good for me?

Related

Split view in two with a menu button? (MFC)

I have an MFC program written that reads files, stores the data, and draws it as text on the client view.
I want to make a menu button View->Split that splits the client area into two, separately scrolling views displaying the same data.
I saw some things about CWndSplitter online and read through some documentation but none of it has proved to be useful because they talk about using OnCreate and deleting the default view to get it to work. This is not an option. I want to keep the default view, but split it in two if the user clicks the button.
I've currently created a CWndSplitter member variable and defined a menu button event handler in my SDI-1View.cpp. When called, it does absolutely nothing but cause the screen to flicker and a second click crashes the program.
void CSDI1View::OnViewSplit32778()
{
// TODO: Add your command handler code here
/*
int rows = 2;
int columns = 1;
if (!m_wndSplitter.CreateStatic(this, rows, columns))
return;
if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS(CSDI1View), CSize(100, 100), NULL) ||
(!m_wndSplitter.CreateView(1, 0, RUNTIME_CLASS(CSDI1View), CSize(100, 100), NULL)))
{
m_wndSplitter.DestroyWindow();
return;
}
*/
}
Can anyone tell me what the normal approach to splitting a client view in half is? I just want to integrate that into an event handler.
Any help would be greatly appreciated.
Thanks.
--------------------------------EDIT----------------------------------
I now have the following code in my Split button event handler, thanks to the outline provided by xMRi, but it is still not working properly...
void CMainFrame::OnViewSplit()
{
// TODO: Add your command handler code here
//calculate client size
CRect cr;
GetClientRect(&cr);
if (!m_mainSplitter.CreateStatic(this, 2, 1))
{
MessageBox(_T("Error setting up splitter frames! (CreateStatic)"),
_T("Init Error!"), MB_OK | MB_ICONERROR);
return;
}
// Set the parent of the splitter window to the current view
CSDI1View * view = CSDI1View::GetView();
m_mainSplitter.SetParent(this);
view->SetParent(&m_mainSplitter);
// Create a CCreateContext
CCreateContext cc;
CRuntimeClass* prt = RUNTIME_CLASS(CSDI1View);
cc.m_pNewViewClass = prt;
cc.m_pCurrentDoc = view->GetDocument();
cc.m_pNewDocTemplate = NULL;
cc.m_pLastView = NULL;
cc.m_pCurrentFrame = this;
if (!m_mainSplitter.CreateView(0, 0,
cc.m_pNewViewClass,
CSize(cr.Width(), cr.Height()/2), &cc))
{
MessageBox(_T("Error setting up splitter frames! (CreateView 1)"),
_T("Init Error!"), MB_OK | MB_ICONERROR);
return;
}
if (!m_mainSplitter.CreateView(1, 0,
cc.m_pNewViewClass,
CSize(cr.Width(), cr.Height()/2), &cc))
{
MessageBox(_T("Error setting up splitter frames! (CreateView 2)"),
_T("Init Error!"), MB_OK | MB_ICONERROR);
return;
}
m_bInitSplitter = TRUE;
}
Upon clicking the view->split button, I get a "Debug Assertion Error" popup and the first call to CreateView returns FALSE, displaying my messagebox: "Error setting up splitter frames! (CreateView 1)"
A static splitter is for a static split--i.e., a window that's always split. You usually use it when you want to have a different view in each pane of the split (e.g. display a column of numbers in one pane, and a graph in the other pane).
For a situation like yours that you want to be able to have the window, then later split it and have two essentially identical views, you (at least normally) want to use a dynamic splitter.
At least normally, you create the splitter when you create the view. That will create a window that has a handle at the top, right-hand corner that the user pulls down to split the view:
To split the window, the user pulls down on the handle:
When the split is where they want it, they release the mouse button, and the view splits into two separately scrollable sections:
Since you didn't specify whether you wanted vertical or horizontal splitting, I set this one up to allow either or both:
The code for this looks something like this:
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT, CCreateContext* pContext) {
return my_splitter.Create(this,
2, 2, // 2 rows, 2 columns
CSize(20, 20), // minimum pane size
pContext);
}
where my_splitter is defined something like this:
CSplitterWnd my_splitter;
If you want to use a splitter window on demand, you need to change the parent of the current view.
So the steps are:
create a simple SDI application
On demand create a splitter window
Use SetParent to the current view and set it as a parent in the splitter window.
Create another window in the second splitter.
And the way back.
Use SetParent and attach the normal view back to the main frame.
Destroy the splitter
There are active samples how to switch a view in a current document (MSDN). It helps you how IDs must be replaced and changed.

How do I set the checkmark next to a menu item in MFC?

I have a menu bar across the top of my dialog and one of the options is "mode" which contains "normal" and "debug". I'm trying to make it so that when the user clicks either of these two options, a checkmark will appear next to the last selected item in the dropdown menu.
This is what I found from searching around google, but I can't get it to work:
//event handler for user clicking on mode then normal in the menu
void CNew_RGB_ControlDlg::OnModeNormal()
{
//check the normal option when the user selects normal mode in the menu
CMenu menu;
menu.LoadMenu(IDR_MENU1);
menu.CheckMenuItem(ID_MODE_NORMAL, MF_CHECKED | MF_BYCOMMAND); //returns 8
menu.CheckMenuItem(ID_MODE_DEBUG, MF_UNCHECKED | MF_BYCOMMAND);//returns 0
}
I also have another of these functions for when debug is clicked, its the same code just the checked and unchecked are switched.
The return values make it seem like it should be working according to MSDN, but the menu items never change.
I have also tried this:
void CNew_RGB_ControlDlg::OnModeNormal()
{
CMenu menu;
menu.LoadMenu(IDR_MENU1);
menu.GetSubMenu(1)->CheckMenuItem(0, MF_BYPOSITION|MF_CHECKED);
menu.GetSubMenu(1)->CheckMenuItem(1, MF_BYPOSITION|MF_CHECKED);
}
What am I doing wrong? What do I need to do to make this work?
Instead of loading a fresh menu when an item is selected, you would need to get the current menu used in the dialog, like
CMenu *pMenu = GetMenu();
if (pMenu != NULL)
{ pMenu->CheckMenuItem(ID_MODE_NORMAL, MF_CHECKED | MF_BYCOMMAND);
pMenu->CheckMenuItem(ID_MODE_DEBUG, MF_UNCHECKED | MF_BYCOMMAND);
}
Declare your CMenu item as a member of the dialog class so it persists after you load the resource the first time, by declaring it in the handler and loading it you are operating on a different copy of the menu each time. You could also load it dynamically each time using ::GetMenu() as another response shows.
When you create the menu before displaying it you have to check the menu item you want and uncheck the others something like this:
// in CNew_RGB_ControlDlg.h
CMenu menu;
// in CNew_RGB_ControlDlg::OnInitDialog
// no need to get submenu if you use the menu id
menu.LoadMenu(IDR_MENU1);
menu.CheckMenuItem(ID_NORMAL, MF_CHECKED);
menu.CheckMenuItem(ID_DEBUG, MF_UNCHECKED);
}
When you respond to the command that set a different menu item as checked
switch(Command)
{
case ID_NORMAL:
menu.CheckMenuItem(ID_NORMAL, MF_CHECKED);
menu.CheckMenuItem(ID_DEBUG, MF_UNCHECKED);
break;
case ID_DEBUG:
menu.CheckMenuItem(ID_NORMAL, MF_UNCHECKED);
menu.CheckMenuItem(ID_DEBUG, MF_CHECKED);
break;
};
Any way to check/uncheck a menu item on the main menu bar?
My old code (from View Class)
CWnd* pParent = GetParent();
CMenu* pMenu = pParent->GetMenu();
pMenu->CheckMenuItem(ID_TEST_1, MF_UNCHECKED);
pMenu->CheckMenuItem(ID_TEST_2, MF_UNCHECKED);
No longer works in VC++ 2010. They say it has something to do with floating toolbars and/or active accessibility.
Nat Hager

MDI MFC VC++ how to switch views within mainframe

I am making MDI application , and without using splitter my document has multiple views. Now i want to change the document view from the MainFrame of an application...
here it is what i am doing , i have outlookbar with some menu buttons, when user will click those buttons then i will show CFormView inside the document as a child instead of popup dialog. Now i dont know how to change the view from MainFrame where the menu handler has been written.
Kindly suggest any tip if you know any...there are more than 5 different views and 4 of them are CFormView.
MainFrame ->MenuhandlerFunction (Menu Clicks)
MenuHandlerFunction -> Open New Document with New View Based on CFormView
(total 5 different CFormView and their handlers inside MainFrame Written)
I'm not very sure how you select which view to display, but here is some code to iterate through the views of the current document in your MainFrame:
EDIT: modified code for MDI
CMDIChildWnd *pChild = (CMDIChildWnd*)GetActiveFrame(); // EDIT: added line
CDocument *pDoc = pChild->GetActiveDocument(); // EDIT: added pChild->
POSITION pos = pDoc->GetFirstViewPosition();
while (pos != NULL)
{ CView* pView = GetNextView(pos);
// if this is the view you want to activate
// pChild->SetActiveView(pView); // EDIT: added pChild->
}

MFC tooltips only show up on special occasions

I have been tasked with assigning tooltips to each item in a configuration menu. I have completed "adding" the tooltip to each control on the page, but it seems sometimes the tooltip shows up and sometimes it does not, depending on the position of the control on the screen.
To tooltip-erize the pages I first
EnableToolTips(TRUE);
In each CPropertyPage's OnInitDialog method.
I then add the notification map
ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnToolTipText)
With the function OnToolTipText looking as such
BOOL CCfgPrefPage::OnToolTipText( UINT id, NMHDR * pNMHDR, LRESULT * pResult )
{
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
UINT nID = pNMHDR->idFrom;
if (pTTT->uFlags & TTF_IDISHWND)
{
nID = ::GetDlgCtrlID((HWND)nID);
if(nID)
{
if( nID == GetDlgItem(IDC_PICKDIST_EDIT)->GetDlgCtrlID())
_tcsncpy_s(pTTT->szText, _T("Tool Tip Text"), _TRUNCATE);
else if( nID == GetDlgItem(IDC_ENDPTTOL_EDIT)->GetDlgCtrlID())
_tcsncpy_s(pTTT->szText, _T("Tool Tip Text"), _TRUNCATE);
pTTT->lpszText = pTTT->szText; // Sanity Check
pTTT->hinst = AfxGetResourceHandle(); // Don't think this is needed at all
return TRUE;
}
}
return FALSE;
}
It seems for some of my controls the tool tip will not show up. For most of the check box controls the tool tip displays, but for a few they just do not show. There are no other controls covering them up, they are not disabled.
Another thing, if I use the non-standard cursor windows repeatedly flashes the tool tip, so much so it is unreadable in some cases. How can I fix this? This is not a problem on CEdit controls, so why is it a problem elsewhere?
EDIT: Update, the controls that have been on the pages for years seem to show tool tips. Any control that I try to add now/today will not show tool tips at all. No matter the position, control type, settings, I cannot get a single tool tip to show on a newly inserted control.
If you do not want to use helper class I have proposed then fix the problems in your code.
First, use ON_NOTIFY_EX_RANGE macro when mapping the even handler, like this (this will cover all IDs):
ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipText)
Next, you need to fix your function. I see a few problems here. First, when testing for TTF_IDISHWND flag you only need to re-initalise the nID. You do not need to apply this to the whole function. Second, after all manipulations, your nID will be the actual dialog ID. There is no need to GetDlgItem() function
BOOL CCfgPrefPage::OnToolTipText( UINT id, NMHDR * pNMHDR, LRESULT * pResult )
{
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
UINT nID = pNMHDR->idFrom;
if (pTTT->uFlags & TTF_IDISHWND)
{
nID = ::GetDlgCtrlID((HWND)nID);
}
if(nID)
{
if( nID == IDC_PICKDIST_EDIT)
_tcsncpy_s(pTTT->szText, _T("Tool Tip Text"), _TRUNCATE);
else if( nID == IDC_ENDPTTOL_EDIT)
_tcsncpy_s(pTTT->szText, _T("Tool Tip Text"), _TRUNCATE);
//pTTT->lpszText = pTTT->szText; // Sanity Check
*pResult = 0;
return TRUE;
}
return FALSE;
}
Working with a toolbar which repeats some menu items from menus of an older MFC application, I have worked on this issue of tool tips as well as (1) modifying the toolbar bit map to include additional icons and (2) providing user feedback on current application state. My problem is that I have to do most of this by hand rather than using the various wizards and tools.
What I have done is to (1) add new members to the CView derived class to handle additional messages, (2) modified the toolbar bit map to add in the additional icons using both MS Paint and the Resource Editor, and (3) added new event ids and event handlers to the message map for the CView derived class.
One problem I ran into with the toolbar bitmap change was that since I was inserting an icon, I had to shift an existing icon in the bitmap to the right. My first attempt at this resulted in the shifted icon showing as a blank on the application toolbar. Then I realized that I needed to add a bit more to the length of the toolbar bitmap. After adding a couple more columns to the last icon in the toolbar bitmap to make it a standard width in pixels, the icon displayed properly.
For tooltips I added the following to the message map:
ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnToolTipText)
I then added the following method to my class to handle the notifications for my menu items. As a side note, it appears that OnToolTipText() is the standard method used in CFrameWnd class and CMDIChildWnd class however CView derives from CWnd as does CFrameWnd so I doubt it makes a difference as to what the method is named.
inline BOOL CPCSampleView::OnToolTipText( UINT id, NMHDR * pNMHDR, LRESULT * pResult )
{
static wchar_t toolTextToggleExportSylk [64] = L"Toggle SYLK export.";
static wchar_t toolTextClearWindow [64] = L"Clear the log displayed.";
static wchar_t toolTextConnectLan [64] = L"Log on the POS terminal through the LAN.";
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
switch (pNMHDR->idFrom) {
case ID_TOGGLE_SYLK_EXPORT:
pTTT->lpszText = toolTextToggleExportSylk;
return TRUE;
case ID_WINDOW_CLEAR:
pTTT->lpszText = toolTextClearWindow;
return TRUE;
case ID_CONNECT_LAN_ON:
pTTT->lpszText = toolTextConnectLan;
return TRUE;
}
// if we do not handle the message then return FALSE to let someone else do it.
return FALSE;
}
For the user feedback on a menu item which toggles a file export when doing reports I provided the following changes to the message map and then implemented the necessary methods. There are two types of messages involved so I had to add two methods and two new message map entries:
// New message map entries to handle the menu item selection event
// and to update the menu item and the toolbar icon with state changes
ON_COMMAND(ID_TOGGLE_SYLK_EXPORT, OnToggleExportSylk)
ON_UPDATE_COMMAND_UI(ID_TOGGLE_SYLK_EXPORT, OnUpdateToggleExportSylk)
// New methods added to the CView derived class
// handle the menu selection event generated by either selecting the menu item
// from the menu or by clicking on the icon in the toolbar.
void CPCSampleView::OnToggleExportSylk()
{
// Exclusive Or to toggle the indicator bit from 0 to 1 and 1 to 0.
GetDocument()->ulReportOptionsMap ^= CPCSampleDoc::ulReportOptionsExportSylk;
}
// handle the request from the MFC framework to update the displayed state this
// not only does a check mark against the menu item it also causes the toolbar
// icon to appear depressed if click is set or non-depressed if click is not set
inline void CPCSampleView::OnUpdateToggleExportSylk (CCmdUI* pCmdUI)
{
if (GetDocument()->ulReportOptionsMap & CPCSampleDoc::ulReportOptionsExportSylk)
{
// SYLK export is turned on so indicate status to the user. This will
// put a check mark beside the menu item and show the toolbar button depressed
pCmdUI->SetCheck (1);
}
else
{
// SYLK export is turned off so indicate status to the user. This will
// remove the check mark beside the menu item and show the toolbar button as raised.
pCmdUI->SetCheck (0);
}
}
The resource file changes were needed to provide a new button for the toggle action as well as to add a new menu item for the toggle action. I am using the same resource id for several different things since these are all separate. So the id for the resource string is the same as for the menu item and is same for the toolbar button so as to simplify my life and make it easy to find all the particular bits and pieces.
The toolbar resource file definition looks like:
IDR_MAINFRAME TOOLBAR 16, 15
BEGIN
BUTTON ID_CONNECT_LAN_ON
SEPARATOR
BUTTON ID_WINDOW_CLEAR
SEPARATOR
BUTTON ID_TOGGLE_SYLK_EXPORT
SEPARATOR
BUTTON ID_APP_ABOUT
END
And the specific part of the menu, which uses the same resource id for the toggle event id looks like:
MENUITEM "Export to SYLK file", ID_TOGGLE_SYLK_EXPORT
Then to provide the status bar text which shows up with a mouse over there is a string table addition:
ID_TOGGLE_SYLK_EXPORT "Toggle export of SYLK format report files for spreadsheets."
The lpszText member of the struct is describe in the MSDN documentation for the TOOLINFO struct as:
Pointer to the buffer that contains the text for the tool, or
identifier of the string resource that contains the text. This member
is sometimes used to return values. If you need to examine the
returned value, must point to a valid buffer of sufficient size.
Otherwise, it can be set to NULL. If lpszText is set to
LPSTR_TEXTCALLBACK, the control sends the TTN_GETDISPINFO notification
code to the owner window to retrieve the text.
Reviewing the existing answer to this question, I wondered about the if statement check for the TTF_IDISHWND flag. The MSDN documentation for the TOOLINFO struct has this to say:
Indicates that the uId member is the window handle to the tool. If
this flag is not set, uId is the tool's identifier.

Killing the focus isn't killing the focus

Here is what I'm doing. I'v created a combobox but I'm not using it for that. When I click it, it calls trackpopup and brings up a context menu. However after I'v clicked the context menu, I'd like it to close the combobox in the same way it would if you clicked anywhere (killing the focus) or selected an item from the combobox.
Here's the event for the combobox:
if(uMsg == WM_COMMAND)
{
HMENU m;
m = CreatePopupMenu();
MENUITEMINFO itm;
itm.cbSize = sizeof(MENUITEMINFO);
itm.fMask = MIIM_FTYPE | MIIM_STRING;
itm.fType = MIIM_STRING;
itm.dwTypeData = "Kill time";
itm.cch = 12;
POINT p;
GetCursorPos(&p);
InsertMenuItem(m,4,false,&itm);
if((int)HIWORD(wParam) == CBN_DROPDOWN)
{
SendMessage(engineGL.controls.TopSelHwnd,WM_KILLFOCUS,(WPARAM)engineGL.controls.TopSelHwnd,0);
SendMessage(engineGL.controls.TopSelHwnd,WM_IME_SETCONTEXT,(WPARAM)0,(LPARAM)ISC_SHOWUIALL);
TrackPopupMenu(m,0,p.x,p.y,NULL,hWnd,NULL);
SendMessage(hWnd,WM_KILLFOCUS,0,0);
SetFocus(HWND_DESKTOP);
}
return 1;
}
How can I make it so that after I click an item on the context menu, the combobox closes properly as if I'd actually chosen an item from it?
Thanks
I'm not sure. Need to try your code.
However I'm sure that one should not send the WM_KILLFOCUS message manually. Instead you need to set the focus to another window by calling SetFocus. The OS will automatically send messages to the window losing the focus and the new window that is gaining the focus.