How might I obtain the IContextMenu that is displayed in an IShellView context menu? - c++

Building a file open dialog replacement. Much of it works now, but I would like to generate the view-mode drop-down for the toolbar directly from the shell view object.
Looking at IShellView2, I can see IShellView2::GetView() will give me the FOLDERVIEWMODE's supported. However, that doesn't give me the names of these modes, nor format that popup menu for me, nor immediately give me a way to actually set one of those modes (it would appear it is necessary to destroy the shell view window and create a replacement one for the current folder and specify the new FOLDERVIEWMODE desired... yeesh).
At any rate, if one right clicks on an IShellView window, one gets a context menu, the first submenu of which is exactly what I want to place in my drop-down toolbar button (ie. the "view" fly-out menu (e.g. Small Icons, Medium Icons, etc.)).
It seems like there ought to be a way to grab that submenu directly from the IShellView, rather than having to hardcode my values (and that way, if a given instance of IShellView supports extra view modes, they'd be there. Similarly, those which should be disabled would be, since it would all be under the IShellView's control).
I have read Raymond Chen's excellent How to host an IContextMenu. Unfortunately, that just gives me a very simplistic context menu - the one for the folder itself, or for a file in a given folder, but NOT the context menu for the IShellView's shell view window (from which I might obtain the view fly-out).
I have tried the following, based on Chen's article:
CComQIPtr<IContextMenu> pcm(m_shell_view); // <<-- FAIL resulting pointer is NULL <<<
// create a blank menu
CMenu menu;
if (!menu.CreatePopupMenu())
throw CContextException("Unable to create an empty menu in which to store the context menu: ");
// obtain the full popup menu we need
if (FAILED(m_hresult = pcm->QueryContextMenu(menu, 0, SCRATCH_QCM_FIRST, SCRATCH_QCM_LAST, CMF_NORMAL)))
throw CLabeledException("Unable to query the context menu for the current folder");
// display the menu to the user
// menu.getsubmenu
::TrackPopupMenu(menu, ::GetSystemMetrics(SM_MENUDROPALIGNMENT)|TPM_TOPALIGN|TPM_LEFTBUTTON, pt.x, pt.y, 0, m_shell_view_hwnd, NULL);
Unfortunately, the attempt to query the m_shell_view (which is an IShellView*) for its IContextMenu interface fails. This "works":
// retrieve our current folder's PIDL
PidlUtils::Pidl pidl(m_folder);
// get the context menu for the current folder
CComPtr<IContextMenu> pcm;
if (FAILED(m_hresult = GetUIObjectOf(m_owner->m_hWnd, pidl, IID_PPV_ARGS(&pcm))))
throw CLabeledException("Unable to obtain the PIDL for the current folder");
But here I get only a very few options in the context menu (Open, Explore, ...). Not the detailed context menu that I get if I simply right click on the shell view itself.
I'm out of ideas as to how to proceed. Help?! ;)

Try IShellView::GetItemObject with SVGIO_BACKGROUND as uItem to get a IContextMenu on the view object : http://msdn.microsoft.com/en-us/library/bb774832%28VS.85%29.aspx

There is the SHCreateDefaultContextMenu (Vista an up) that may be of help. Bjarke Viksoe website contains great info as well.
SVGIO_BACKGROUND will get you the background context menu of the shell view. You may need to call repeatedly pShellView->SelectItem for each PIDL you may have, then do the GetUIObjectOf call (then QI for IContextMenu, create a menu, call IContextMenu(3)::QueryContextMenu and finally display it with TrackPopupMenu).

Related

Disable some context menu items if no items are checked

I have a tree view (CTreeView) that will show me a pop-up menu after I right-click my mouse on it.
In my context menu there are only 3 items (i.e A, B, C) for selection and my tree view displays a long list of ordered foods designed with check-boxes. I would like to disable menu items A and B if no ordered foods are checked and enable them when any is.
I create CFoodView::OnUpdateItemA(CCmdUI* pCmdUI) //CFoodView inherits CTreeView
and CFoodView::OnUpdateItemB(CCmdUI* pCmdUI) to handle their states like so
CFoodView::OnUpdateItemB(CCmdUI* pCmdUI)
{
if TreeView has no items
{
pCmdUI->Enable(FALSE);
}
else
{
*Search* the tree to get selected items
if None is checked
{
pCmdUI->Enable(FALSE);
}
else there are checked items
pCmdUI->Enable(TRUE);
}
}
Method CFoodView::OnUpdateItemA(CCmdUI* pCmdUI) is the same.
I think this isn't a correct way to handle this GUI feature.
Well, you did not submit all important information. How did you create menu item handlers?
Assuming you insert handlers the proper way, still did not provide any information how you are invoking popup menu.
If all you did was properly done it is the proper way of handling update menu.
The most common mistake is designating view itself as the window that handles popup updates and commands. In order to use MFC menu update mechanism, you have to pass a pointer to the main window not to the tree view:
CWnd *pMainWnd = AfxGetMainWnd();
ASSERT(pMainWnd != nullptr);
pSubMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, pMainWnd);
If this will not work reexamine the way you create handler and/or the place you invoke the TrackPopupMenu function.

Adding and localizing menu items in the main menu of a Qt application menubar

So first of all here is a screenshot of the said menu of Evernote, localized in French:
[]
As you can see, all the menu items in the main menu (by main menu I mean the one whose name is the application name, like here it is Evernote) are localized in French. There are lots of menu items which the Evernote app itself brings, like Évaluez Evernote pour Mac (Rate Evernote for Mac), Information du compte... (Account Info...), etc. Plus there are the standard OS X provided menu items like Quit Evernote, Preferences, etc which are also localized.
My questions:
How do I add a new item in this main menu? How to access this menu to add items?
How do I localize these items based on my app localization, both OS X provided default ones and the ones I add?
In the Evernote menu, everything seems to be localized except the Services menu option (the submenu options are however localized!)? Can't this be localized as well?
What I have tried:
fMenuBar = fMainWindow->menuBar();
fMenuFile = fMenuBar->addMenu(QObject::tr(qPrintable(String_Class::FileMenu))); //"File" in English, translated into other languages
fAboutAppAct = new QAction(QObject::tr(qPrintable(String_Class::About_App)), fMainWindow); //prints "About App", localized in all languages
fMenuFile->addAction(fAboutAppAct);
fAboutAppAct->setMenuRole(QAction::AboutRole); //otherwise it sits with the other file menu options in the File menu
//reset UI language slot, called whenver UI language is reset. It retranslates all strings in all menus, except this
void AppMenu::reTranslateUISlot()
{
fAboutAppAct->setText(QObject::tr(qPrintable(String_Class::About_App)));
}
Maybe you could reimplement in MainWindow or in AppMenu the changeEvent.
void MainWindow::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange) {
this->retranslateUi(this);
quickStart->retranslateUi(quickStart);
//etc...
} else {
QMainWindow::changeEvent(event);
}
}
You could force Widgets to retranslate themselves. But you need to have registered some QTranslator first.
For example, in the constructor of MainWindow (or in some config dialog) if it's possible to change language at runtime (what I've done in my software):
CustomizeOptionsDialog::CustomizeOptionsDialog(QWidget *parent)
: QDialog(parent, Qt::Tool)
{
// Load the language of the application
customTranslator.load(languages.value( SettingsPrivate::instance()->language()) );
// Translate standard buttons (OK, Cancel, ...)
defaultQtTranslator.load("qt_" + SettingsPrivate::instance()->language(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
QApplication::installTranslator(&customTranslator);
QApplication::installTranslator(&defaultQtTranslator);
}
Where language() returns "fr", "gb" or "cs" (initialized from a signal emitted when one has chosen a new language in options).
/** Change language at runtime. */
void CustomizeOptionsDialog::changeLanguage(const QString &language)
{
QString lang = languages.value(language);
SettingsPrivate *settings = SettingsPrivate::instance();
// If the language is successfully loaded, tells every widget that they need to be redisplayed
if (!lang.isEmpty() && lang != settings->language() && customTranslator.load(lang)) {
settings->setLanguage(language);
defaultQtTranslator.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
QApplication::installTranslator(&customTranslator);
/// TODO: reload plugin UI
QApplication::installTranslator(&defaultQtTranslator);
} else {
labelStatusLanguage->setText(tr("No translation is available for this language :("));
}
}
I hope it's helping.
I still haven't found the complete answer to my problems. But here some of the observations I have made over the last few days:
To be able to add menu items in the main menu, you have to set the menu role accordingly, i.e after adding it wherever you want to (it won't matter, because it will move out), you set the menu role like this:
fYourAction->setMenuRole(QAction::ApplicationSpecificRole);
This will add the menu item in the main menu. If you add more than item in this way, they will appear in the order in which you set their menu roles.
There are few specific roles Qt already provides - i.e for the About <app> item, Quit <app> item, Preferences... item, etc. They are mentioned here.
For example, if your action has a text "Foo", and you add it somewhere as a menu item, and set the role like
fFooAction->setMenuRole(QAction:: PreferencesRole);
then it will automatically move to the main menu and show as Preferences..., what text you actually put in the action will be immaterial. Whatever slot you have attached to it as a response to the triggered() signal will still fire correctly, though. Same goes for QAction::AboutRole as well, whatever text you add in that action, it will move to the main menu and show as About <your_app_name>.
The problem with QAction::AboutRole or QAction:: PreferencesRole is like I said, they won't localize even if you try. They will get localized only when the system locale changes, if you change it just within your app by installing a new translator, it won't change. The workaround? Avoid them and use QAction::ApplicationSpecificRole for all items you want to appear in the main menu. Then they will get properly localized as per your custom translator, and will respect whatever text you provide in the action, i.e if you give foo as text in the action, it will appear as foo in the main menu, and get localized accordingly. Again, mind you, when you are adding multiple items, set the role of the items in order of their appearance, i.e to simulate the Evernote menu above, first set the menu role for the about_app action, then the preferences action. Where you are adding them will be of no importance since they will be moved to a new menu, so the order in which you set the menu role for the items will determine the order in which they appear in the main menu.
The problem with the above approach is that I don't know how to insert separators between the items I am adding in the main menu. It is easy to do that in the menus we add, since we have access to the menu object, but here we don't have access (we add the items somewhere else, and make them move to the main menu by setting the menu role), so I don't know yet how to add multiple separators in the main menu.

Best way to Enable/Disable CMenu items in real time

I'm working on a project using Visual C++ 6.0, and I need to be able to enable or disable certain menu items depending on the permissions assigned to the currently logged in user. This is the code I'm using:
// If the currently logged in user doesn't have permission to edit invoices
if (!((CMyApp *)AfxGetApp())->UserHasPermission(PERMISSION_EditInvoice))
{
// Disable the Edit Menu
pMain->EnableMenuItem(1, MF_BYPOSITION | MF_DISABLED | MF_GRAYED);
}
else
{
// Enable the Edit Menu
pMain->EnableMenuItem(1, MF_BYPOSITION | MF_ENABLED);
}
It does exactly what I want it to do, however I'm trying to find the best place to put it. If I put it in OnInitialUpdate(), I get the results I want, but only for the first invoice opened. If you open a second invoice without closing and re-opening the dialog, the code is not executed again. OnUpdate() isn't called when opening a different invoice, and the only other place I've found that works is OnDraw(), the problem with OnDraw() is that the menu item doesn't visually change state from Grayed out to Enabled or vice versa until you try to click it.
I think you must include this code in a procedure
void check_user_permission();
than you must call it when this events occur:
- OnInitialUpdate()
- new user login (if your software permits user login/logout during the same session)
- new invoice opened
Can it help?
I ended up deciding to disable the Edit Invoice menu item, instead of the Edit menu itself. This proved much easier and cleaner, as it determines permission and enables or disables item every time the main 'Edit menu is opened.
void CViewInvoiceView::OnUpdateEditEditinvoice(CCmdUI* pCmdUI)
{
// If the currently logged in user doesn't have permission to edit invoices
if (!((CJ3App *)AfxGetApp())->UserHasPermission(PERMISSION_EditInvoice))
{
// Disable the Edit Menu
pCmdUI->Enable(false);
}
else
{
// Enable the edit menu
pCmdUI->Enable();
}
}

Problems with CMenu::ModifyMenu

I'm using CMenu::ModifyMenu in the OnCreate method of my CFrameWnd derived class to change the captions on my menu to match the user language.
I'm using VC++ designer and the menu is declared in a .rc file.
For the MENUITEM elements I use it as follow:
m_wndMenu->ModifyMenu(ID_APP_EXIT, MF_BYCOMMAND, NULL, CString((LPWSTR) ID_APP_EXIT));
For the POPUP elements (that don't have an ID) I use it as follow:
m_wndMenu->ModifyMenu(0, MF_BYPOSITION | MF_STRING, NULL, CString((LPWSTR) ID_MENU_POPUP_FILE));
It works as expected to change the captions, but for the menu items that are initialy disabled when I change the caption they get enabled. How do I fix this?
You may have to explicitly disable the menu item and set tool tip text after a call to ModifyMenu. Using ModifyMenu will effectively destroy the previous menu item and create a new one. You are losing any settings and initialization from the resource file or otherwise that you had on the previous item or menu.
See remarks: http://msdn.microsoft.com/en-us/library/4tbfebs6(v=vs.80).aspx
for such scenario, better to use EnableMenuItem function, like this
m_wndMenu->EnableMenuItem(ID_APP_EXIT, MF_BYCOMMAND| MF_ENABLED);
this will work...

How do I display a tooltip for a CMFCRibbonButton in the status bar?

I have a CMFCRibbonStatusBar in my mainframe to which I add a CMFCRibbonButtonsGroup which again has a CMFCRibbonButton. This button has the same ID as a menu entry.
Creating the button is done as follows:
CMFCRibbonButtonsGroup* pBGroup = new CMFCRibbonButtonsGroup();
CMFCToolBarImages images;
images.SetImageSize(CSize(32, 16)); // Non-square bitmaps
if(images.Load(IDB_STATUSBAR_IMAGES))
{
pBGroup->SetImages(&images, NULL, NULL);
}
m_pStatusButton = new CMFCRibbonButton(ID_STATUS_SHOWSTATUS,
_T(""),
IMAGEINDEX_DEFAULTSTATUS);
pBGroup->AddButton(m_pStatusButton);
m_wndStatusBar.AddExtendedElement(pBGroup, _T(""));
I want to use this button as a status indicator.
I want to display a tool tip in the following two cases:
when the status changes and
when the user moves the mouse over the button.
I have no idea how to start in the first place. I have looked at the ToolTipDemo and DlgToolTips sample projects but couldn't figure out how to do it since all they do is display tooltips for the toolbar items or dialog buttons (CWnd-derived instead of CMFCRibbonButton).
If you are familiar with the ToolTipDemo sample project: Since there seem to be several ways of doing things, I would prefer the tooltip to look like the "Extended Visual Manager-based" tool tip as shown in this screenshot.
Thanks!
I don't think it's possible to show the tooltip without the mouse cursor being over the control. That's all done automatically.
However if you want to have a nice looking tooltip like in your screenshot, you need to call SetToolTipText and SetDescription, like this:
CMFCRibbonButton* pBtn = new CMFCRibbonButton(12345, _T(""), 1);
pBtn->SetToolTipText("This is the bold Title");
pBtn->SetDescription("This is the not-so-bold Description");
pGroup->AddButton(pBtn);
I am using CMFCRibbonButton controls within a CMFCRibbonButtonGroup, which is added to the CMFCRibbonStatusBar. Take note of the 4th parameter in the CMFCRibbonButton() constructor, bAlwaysShowDescription, as this seems to affect the behavior depending upon whether SetDescription() has been called.
Specifically, if SetDescription() has not been called, it doesn't matter whether bAlwaysShowDescription is TRUE or FALSE - the tool tip is displayed (as I would expect). If SetDescription() is set and bAlwaysShowDescription is FALSE, when hovering over the button the tool tip is displayed with the description below it.
What seems counterintuitive given the name of this bAlwaysShowDescription parameter, is that when this is TRUE and SetDescription() is set, NEITHER the tool tip nor the description appear. I wonder if this is related to this post:
https://connect.microsoft.com/VisualStudio/feedback/details/399646/cmfcribbonbutton-wont-show-tooltip-if-balwaysshowdescription-1
Hope this helps and you can achieve what you need with the different combinations of bAlwaysShowDescription parameter and whether SetDescription() is set.