matlabcallbackmatlab-figureacceleratorkey

Using Enter as Accelerator in MATLAB UIMenu


I'm building a GUI in MATLAB and currently adding custom menus using uimenu. I'm trying to add different accelerators to different menu actions.

I've found that passing char(10) (newline) as the accelerator character in uimenu (see below) matlab adds Ctrl+ Enter as that menu's accelerator label. The problem is that it will not run the callback when I hit Ctrl+ Enter.

Any ideas why this doesn't work? Am I missing something? Is the Ctrl+ Enter for "run current section" cancelling my call? In that case, can I override it?

Example

A quick demonstrative example of how MATLAB will not accept Ctrl+ Enter

function test
close all
f=figure;
m=uimenu(f,'Label','test');
uimenu(m,'Label','a','callback',@hittest,'Accelerator','r');
uimenu(m,'Label','b','callback',@hittest,'Accelerator',char(10));

    function hittest(h,~)
        disp(h.Label)
    end
end

Solution

  • As you've stated, it appears the main application has registered this accelerator and is therefore preventing your GUI from intercepting this call.

    You could try to change MATLAB's keyboard shortcut in the shortcut preferences dialog. Note that this will only affect your installation of MATLAB.

    If you start MATLAB in -nodesktop mode, then this will prevent the MATLAB IDE from launching the IDE and should free up the accelerator for your use.

    matlab -nodesktop
    

    Since you mention that this will be a deployed application, you could always use isdeployed to check if it is being run as a deployed application and if it's not then you could use an alternate keyboard shortcut so you don't have to continuously start MATLAB without an IDE

    if ~isdeployed
        % Use some other keyboard shortcut for testing
        set(hmenu, 'Accelerator', <some other key for testing>)
    else
        % Use the enter key on deployed applications
        set(hmenu, 'Accelerator', char(10))
    end
    

    You could also make it so that any time your app is deployed or matlab is being run with -nodesktop it would use the enter key:

    if usejava('desktop')
        % Use some other keyboard shortcut for testing
        set(hmenu, 'Accelerator', <some other key for testing>)
    else
        % Use the enter key on deployed applications
        set(hmenu, 'Accelerator', char(10))
    end