I can create Shortcut key on menu but it does not work.Please help me!

Hi all!
I have a menu named File - under which I have submenus “New”.
Now the Ctr+ N key should be equavalent to clicking on New .
I created shortcut key based on Juce demo example.It displayed Ctr + N on popupMenu.
Now i have problem. When i use Ctr + N , it does not work.
Please help me.
Thanks all.
My code:
MainComponent.h

#ifndef MAINCOMPONENT_H_INCLUDED
#define MAINCOMPONENT_H_INCLUDED

#include "../JuceLibraryCode/JuceHeader.h"

//=============================================================================
/*
    This component lives inside our window, and this is where you should put all
    your controls and content.
*/
class MainContentComponent   : public Component,public MenuBarModel, public ApplicationCommandTarget
{
public:
    //=============================================================================
    MainContentComponent();
    ~MainContentComponent();
	StringArray getMenuBarNames();
	PopupMenu getMenuForIndex(int 	topLevelMenuIndex,
		const String & 	menuName
	);
	void menuItemSelected(int 	menuItemID,
		int 	topLevelMenuIndex
	);
    void paint (Graphics&);
    void resized();
	ApplicationCommandTarget* getNextCommandTarget();
	void getAllCommands(Array<CommandID>& );
	void getCommandInfo(CommandID, ApplicationCommandInfo&);
	bool perform(const InvocationInfo& );
	static ApplicationCommandManager& getApplicationCommandManager();
	enum CommandIDs {
		New = 10
	};
private:
ApplicationCommandManager *commandManager = &MainContentComponent::getApplicationCommandManager();
ScopedPointer<MenuBarComponent> menuBar;
    //==============================================================================
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainContentComponent)
};

MainComponent.cpp :

#include "MainComponent.h"

static ScopedPointer<ApplicationCommandManager> applicationCommandManager;
//==============================================================================
MainContentComponent::MainContentComponent()
{
	menuBar = new MenuBarComponent(this);
	addAndMakeVisible(menuBar);
commandManager->registerAllCommandsForTarget(this);
commandManager->registerAllCommandsForTarget(JUCEApplication::getInstance());
commandManager->setFirstCommandTarget(this);

addKeyListener(commandManager->getKeyMappings());
	setSize(800, 600);
}

MainContentComponent::~MainContentComponent()
{
	applicationCommandManager = nullptr;
}

StringArray MainContentComponent::getMenuBarNames()
{
	const char* menuNames[] = { "File", "View","Help", 0 };
	return StringArray(menuNames);
}

PopupMenu MainContentComponent::getMenuForIndex(int topLevelMenuIndex, const String & menuName)
{
	
	PopupMenu menu;

	if (menuName == "File")
	{

		//menu.addItem(10, "New");

		menu.addCommandItem(commandManager, MainContentComponent::New);

	}
	return menu;
}

void MainContentComponent::menuItemSelected(int menuItemID, int topLevelMenuIndex)

{
	switch (menuItemID)
	{
	case 10:
		AlertWindow::showMessageBoxAsync(AlertWindow::NoIcon, "New", "This is New");
		break;
	default:
		break;
	}
}

void MainContentComponent::paint(Graphics& g)
{
	g.fillAll(Colour(51, 51, 51));

	g.setFont(Font(16.0f));
	g.setColour(Colours::white);
	g.drawText("Hello World!", getLocalBounds(), Justification::centred, true);
}

void MainContentComponent::resized()
{
	menuBar->setBounds(0, 0, getWidth(), 80);

}

ApplicationCommandTarget * MainContentComponent::getNextCommandTarget()
{
	return findFirstTargetParentComponent();
}

void MainContentComponent::getAllCommands(Array<CommandID>& commands)
{
	const CommandID ids[] = { MainContentComponent::New };
	commands.addArray(ids, numElementsInArray(ids));
}

void MainContentComponent::getCommandInfo(CommandID commandID, ApplicationCommandInfo & result)
{
	switch (commandID)
	{
	case MainContentComponent::New:
		result.setInfo("New", String::empty, String::empty, 0);
		result.addDefaultKeypress('N', ModifierKeys::commandModifier);
		break;
	}
}

bool MainContentComponent::perform(const InvocationInfo & info)
{
	switch (info.commandID)
	{
	case MainContentComponent::New:   AlertWindow::showMessageBoxAsync(AlertWindow::NoIcon, "New", "This is New");  break;
	default: break;
	}
	return true;
}

ApplicationCommandManager & MainContentComponent::getApplicationCommandManager()
{

	if (applicationCommandManager == nullptr)
		applicationCommandManager = new ApplicationCommandManager();
	return *applicationCommandManager;
}

Main.cpp :

#include “…/JuceLibraryCode/JuceHeader.h”
#include “MainComponent.h”

//==============================================================================
class LayoutMenuApplication : public JUCEApplication
{
public:
//==============================================================================
LayoutMenuApplication() {}

const String getApplicationName() override       { return ProjectInfo::projectName; }
const String getApplicationVersion() override    { return ProjectInfo::versionString; }
bool moreThanOneInstanceAllowed() override       { return true; }
//==============================================================================
void initialise (const String& commandLine) override
{
    // This method is where you should put your application's initialisation code..
    mainWindow = new MainWindow (getApplicationName());
}
void shutdown() override
{
    // Add your application's shutdown code here..
    mainWindow = nullptr; // (deletes our window)
}
//==============================================================================
void systemRequestedQuit() override
{
    // This is called when the app is being asked to quit: you can ignore this
    // request and let the app carry on running, or call quit() to allow the app to close.
    quit();
}
void anotherInstanceStarted (const String& commandLine) override
{
    // When another instance of the app is launched while this one is running,
    // this method is invoked, and the commandLine parameter tells you what
    // the other instance's command-line arguments were.
}
//==============================================================================
/*
    This class implements the desktop window that contains an instance of
    our MainContentComponent class.
*/
class MainWindow    : public DocumentWindow
{
public:
    MainWindow (String name)  : DocumentWindow (name,
                                                Colours::lightgrey,
                                                DocumentWindow::allButtons)
    {
        setUsingNativeTitleBar (true);
        setContentOwned (new MainContentComponent(), true);
        centreWithSize (getWidth(), getHeight());
        setVisible (true);
    }
    void closeButtonPressed() override
    {
        // This is called when the user tries to close this window. Here, we'll just
        // ask the app to quit when this happens, but you can change this to do
        // whatever you need.
        JUCEApplication::getInstance()->systemRequestedQuit();
    }
    /* Note: Be careful if you override any DocumentWindow methods - the base
       class uses a lot of them, so by overriding you might break its functionality.
       It's best to do all your work in your content component instead, but if
       you really have to override any DocumentWindow methods, make sure your
       subclass also calls the superclass's method.
    */
private:
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
};

private:
ScopedPointer mainWindow;
};

//==============================================================================
// This macro generates the main() routine that launches the app.
START_JUCE_APPLICATION (LayoutMenuApplication)

Please, Can anyone give me some feedback?
Thanks.

Noone help? :sweat:

The way you are setting up your ApplicationCommandManager is extremely unsettling. My suggestion is to look at how it’s setup in a Jucer generated app or in any of the examples.

It looks like you’re trying to do some sort of singleton, and that *commandManager pointer to (static) class function return dereference … Don’t do that.

You don’t really need a global static scoped pointer to an application command manager. Just use a class member variable in the Main application. You will only ever have one main application and you want your command manager to destruct last.

Main.h:

class MyApp : public JuceApplication
{
public:
    //blah blah
     ApplicationCommandManager commandManager;
private:
}

extern ApplicationCommandManager& getCommandManager();

Main.cpp

static MyApp& getApp()           { return *dynamic_cast<MyApp*>(JUCEApplication::getInstance()); }
ApplicationCommandManager& getCommandManager()
{
	return getApp().commandManager;
}

Also, in your perform method, you should only return true if you handed the command. Otherwise return false.

bool MainContentComponent::perform(const InvocationInfo & info)
{
	switch (info.commandID)
	{
	case MainContentComponent::New:   AlertWindow::showMessageBoxAsync(AlertWindow::NoIcon, "New", "This is New");  break;
	default: return false;
	}
	return true;
}

Also, it looks like you have the same handling code in both the ‘perform’ and the ‘menuItemSelected’ methods.

If an application command were properly registered, then when you click on the menu item, you should be getting both a ‘perform’ and ‘menuItemSelected’ event trigger. I guarantee you that if you click ‘New’ on the menu and are only getting one popup dialog box that the command is not properly registered.

If the command is not properly registered (or if this command target is superseded somewhere in the chain and this component is not in the ancestry of the new firstCommandTarget) then the accelerator keys will not work.

@jpoag First of all,thank you for your advice.
I really appreciate your help in resolving my problem.But it still does not work.

The key listener needs to be added on the MainWindow instead of the MainContentComponent:

addKeyListener (MainContentComponent::getApplicationCommandManager().getKeyMappings());

Main.cpp

    class MainWindow    : public DocumentWindow
    {
    public:
        MainWindow (String name)  : DocumentWindow (name,
                                                    Colours::lightgrey,
                                                    DocumentWindow::allButtons)
        {
            setUsingNativeTitleBar (true);
            setContentOwned (new MainContentComponent(), true);

            centreWithSize (getWidth(), getHeight());
            setVisible (true);

			addKeyListener (MainContentComponent::getApplicationCommandManager().getKeyMappings());
        }
1 Like

@jpoag Thank you so much.you are a lifesaver.Hehe. It work. :heart_eyes: