Using Enter as Accelerator in MATLAB UIMenu - matlab

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

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

Related

Run a function after keypress in MATLAB

I want MATLAB to run a function after I press a specific key "s" from the keyboard while I am within the MATLAB application (focused in MATLAB window). Is there a way to do that without the use of any external packages or libraries?
Thank you.
You can set custom shortcuts in Matlab by selecting:
Home > Preferences > Shortcuts
The closest option to what you want is "evaluate entire file" which runs the current script / function file open in the editor. I don't know of any ability to run a specific function using this, but you can assign the shortcut "S" as shown below.

How do I specify the MATLAB editor keybindings programmatically

I want to setup the keyboard keybindings as Windows Default Set and I would like to do this at startup using the startup.m because I want this setting to be set on a large number of systems.
The equivalent setting in the preferences dialog is: MATLAB > Keyboard > Shortcuts > Active Settings: Windows Default Set.
Proposal of startup.m after Suever's answer
See line 8
% TODO set startup script in $HOME/Documents/bin/matlab/startup.m in Terminal
% all commands here will be run at startup etc startup.m
% TODO set user path as relative by $HOME/Documents/bin/matlab/
%userpath('/home/masi/Documents/bin/matlab/')
% TODO How to set up userpath outside this Matlab script in Terminal?
% http://stackoverflow.com/a/38188945/54964
if ( not( com.mathworks.services.Prefs.getStringPref('CurrentKeyBindingSet') == 'Windows' ) )
com.mathworks.services.Prefs.setStringPref('CurrentKeyBindingSet', 'WindowsDefaultSet.xml')
end
% Event errors else with touchpad scroll
!synclient HorizTwoFingerScroll=0
Matlab: 2016a
System: Linux Ubuntu 16.04
If you want to do this programmatically you can do it using the undocumented functions for setting the preferences.
com.mathworks.services.Prefs.setStringPref('CurrentKeyBindingSet', 'Windows')
If you want a different keybinding, you can set the value explicitly from the preferences dialog and then call the following to retrieve the value.
com.mathworks.services.Prefs.getStringPref('CurrentKeyBindingSet')
This command should only have to be run once per MATLAB installation so placing it within the startup.m file may be overkill and would also prevent users from being able to change your default settings.

Matlab control+enter key on figure

I want to capture when the user holds down the control key and presses the enter key on a figure window. Note: This is the default keys for "Evaluate Current Section" in the editor.
See example code below:
function test
f = figure;
f.KeyPressFcn = #myKeyPressFcn;
end
function myKeyPressFcn ( hFig, event )
cm = hFig.CurrentModifier();
if ~isempty ( cm )
fprintf ( 'CurrentKey: %s:%s\n', cm{1}, hFig.CurrentKey );
else
fprintf ( 'CurrentKey: %s\n', hFig.CurrentKey );
end
end
To reproduce save the above in an active file in the editor and run the function - the editor needs to be open (this is important!!).
With the figure active press any key -> the selected key is written to the terminal window. However if you hold down Control and press the enter (return) key then this is not captured but instead Matlab attempts to "Evaluate Current Section" (or cell as it used to be called) in the editor (no matter that the figure has the focus). This of course throws as error...
I have contacted Matlab support and this is "expected behaviour!". I can (just about) see why it might be a good idea for demos - but for professional applications that run in Matlab I personally think this "feature" is a bug!!
Notes
When the editor is closed the control+enter is captured in the figure
In deployed applications the control+enter is captured.
If I manually change the Evaluate Current Section shortcut then control+enter is captured.
I have tried a number of things to resolve this but none have worked, for example hiding the editor or setting editor enable state to false (neither of these are acceptable solutions - I was trying to see what I could get to work on a small test case...):
function test
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
jEditor = desktop.getGroupContainer('Editor').getTopLevelAncestor;
jEditor.setVisible(false);
jEditor.setEnable(false);
f = figure
f.KeyPressFcn = #myKeyPressFcn;
uiwait(f);
jEditor.setVisible(true);
jEditor.setEnable(true);
end
The only way I can get it to work is to close all of the editor files on launching the GUI and then opening them again when the GUI closes (this is not an acceptable solution... - for fairly obvious reasons!!)
I did think about trying to temporarily modify the shortcut key (Preferences-Keyboard-Shortcuts) of the "Evaluate Current Section" -> but haven't worked out a way to do it from the commandline, and then set it back again when finished. If this is fast you could do it when the user presses and releases the control key.
So what am I asking:
If possible I need a solution that will work for anyone anywhere - as if I can get this to work it will be included in a new add-on feature in my Matlab GUI Toolbox. - which is used by people all over the world.
Do you know how to modify the keyboard shortcuts from the commandline - if so how!
Any other suggestions?
My other idea is to change my shortcut to a different key combination - but wheres the fun in that! :) (I will still have the issue if some user somewhere has altered the execute the current cell to my new combination...)
P.S. Thanks for reading this far down!! :)
Why don't you go to the home> Preferences > keyboard > Shortcutand change it there?
you only need to hit Ctrl + Enter in the black box at top of the page for searching the related command, which is here Evaluate Current Section and change it whatever you like.
Please bear in mind you will only need to split out your windows (Undock them). Then, when you click on Ctrl + Enter, it will do whatever you would like.
I hope you find this answer helpful.
You can try the solution from my FEX submission. The KbTimer is motivated by the need to capture keyboard stroke without the need of GUI that designed either by GUIDE or APP DESIGNER. Note that the implementation of function was inspired from the PsychToolbox which is MEX based.

programmatically press an enter key after starting .exe file in Matlab

In Matlab I can start external .exe files that sometime have a pop up that requires an enter key pressed. For example:
system('C:\Program Files (x86)\WinZip\WINZIP32.EXE')
will start Winzip, and then in order to use it you need to pass the "buy now" pop up window by pressing enter.
Now my problem is not with winzip, I only gave it as an example (i use winrar anyway :).
How can I programmatically press an enter key in Matlab in such cases ? (I use win 7)
Can an event listener be used to solve that?
EDIT: The java.awt.Robot class indeed works on explorer, but not on any software that has a pop up window with an OK button that needs to be pressed. I don't know why it doesn't work for that. I gave the winzip example because I assume everybody has winzip/winrar installed in their machine. The actual software I have is different and irrelevant for the question.
There is a way using Java from Matlab, specifically the java.awt.Robot class. See here.
Apparently there are two types of programs, regarding the way they work when called from Matlab with system('...'):
For some programs, Matlab waits until the program has finished before running the next statement. This happens for example with WinRAR (at least in my Windows 7 machine).
For other programs this doesn't happen, and Matlab proceeds with the next statement right after the external program has been started. An example of this type is explorer (the standard Windows file explorer).
Now, it is possible to return execution to Matlab immediately even for type 1 programs: just add & at the end of the string passed to system. This is standard in Linux Bash shell, and it also works in Windows, as discussed here.
So, you would proceed as follows:
robot = java.awt.Robot;
command = '"C:\Program Files (x86)\WinRAR\WinRAR"'; %// external program; full path
system([command ' &']); %// note: ' &' at the end
pause(5) %// allow some time for the external program to start
robot.keyPress (java.awt.event.KeyEvent.VK_ENTER); %// press "enter" key
robot.keyRelease (java.awt.event.KeyEvent.VK_ENTER); %// release "enter" key
If your applications are only on Windows platform, you can try using .net objects.
The SendWait method of the SendKeys objects allows to send virtually any key, or key combination, to the application which has the focus, including the "modifier" keys like Alt, Shift, Ctrl etc ...
The first thing to do is to import the .net library, then the full syntax to send the ENTER key would be:
NET.addAssembly('System.Windows.Forms');
System.Windows.Forms.SendKeys.SendWait('{ENTER}'); %// send the key "ENTER"
If you only do it once the full syntax is OK. If you plan to make extensive use of the command, you can help yourself with an anonymous helper function.
A little example with notepad
%% // import the .NET assembly and define helper function
NET.addAssembly('System.Windows.Forms');
sendkey = #(strkey) System.Windows.Forms.SendKeys.SendWait(strkey) ;
%% // prepare a few things to send to the notepad
str1 = 'Hello World' ;
str2 = 'OMG ... my notepad is alive' ;
file2save = [pwd '\SelfSaveTest.txt'] ;
if exist(file2save,'file')==2 ; delete(file2save) ; end %// this is just in case you run the test multiple times.
%% // go for it
%// write a few things, save the file then close it.
system('notepad &') ; %// Start notepad, without matlab waiting for the return value
sendkey(str1) %// send a full string to the notepad
sendkey('{ENTER}'); %// send the {ENTER} key
sendkey(str2) %// send another full string to the notepad
sendkey('{! 3}'); %// note how you can REPEAT a key send instruction
sendkey('%(FA)'); %// Send key combination to open the "save as..." dialog
pause(1) %// little pause to make sure your hard drive is ready before continuing
sendkey(file2save); %// Send the name (full path) of the file to save to the dialog
sendkey('{ENTER}'); %// validate
pause(3) %// just wait a bit so you can see you file is now saved (check the titlebar of the notepad)
sendkey('%(FX)'); %// Bye bye ... close the Notepad
As explained in the Microsoft documentation the SendKeys class may have some timing issues sometimes so if you want to do complex manipulations (like Tab multiple times to change the button you actually want to press), you may have to introduce a pause in your Matlab calls to SendKeys.
Try without first, but don't forget you are managing a process from another without any synchronization between them, so timing all that can require a bit of trial and error before you get it right, at least for complex sequences (simple one should be straightforward).
In my case above for example I am running all my data from an external hard drive with an ECO function which puts it into standby, so when I called the "save as..." dialog, it takes time for it to display because the HDD has to wake up. If I didn't introduce the pause(1), sometimes the file path would be imcomplete (the first part of the path was send before the dialog had the focus).
Also, do not forget the & character when you execute the external program. All credit to Luis Mendo for highlighting it. (I tend to forget how important it is because I use it by default. I only omit it if I have to specifically wait for a return value from the program, otherwise I let it run on its own)
The special characters have a special code. Here are a few:
Shift +
Control (Ctrl) ^
Alt %
Tab {TAB}
Backspace {BACKSPACE}, {BS}, or {BKSP}
Validation {ENTER} or ~ (a tilde)
Ins Or Insert {INSERT} or {INS}
Delete {DELETE} or {DEL}
Text Navigation {HOME} {END} {PGDN} {PGUP}
Arrow Keys {UP} {RIGHT} {DOWN} {LEFT}
Escape {ESC}
Function Keys {F1} ... {F16}
Print Screen {PRTSC}
Break {BREAK}
The full list from Microsoft can be found here
There is a small javascript utility that simulates keystrokes like this on the Windows javascript interpreter.
Just create a js file with following code:
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
then call it from Matlab after the necessary timeout like this:
system('c:\my\js\file\script.js {Enter}');
Can't test here now, but I think this should work...
If you need to run a console-only program in a context that permits full DOS redirection, you can create a file called, say, CR.txt containing a carriage return and use the '<' notation to pipe the value into the program.
This only works if you can provide all the keyboard input can be recorded in the file. It fails dismally if the input has to vary based on responses.
An alternative is to duplicate the input (and possibly output) stream(s) for the program and then pipe data into and out of the program. This is more robust and can permit dynamic responses to the data, but will also likely require substantial effort to implement a robot user to the application.
Rog-O-Matic is an example of a large application completely controlled by a program that monitors screen output and simulates keyboard input to play an early (1980s) ASCII graphic adventure game.
The other responses will be required for GUI-based applications.
Python package pywinauto can wait any dialog and click buttons automatically. But it's capable for native and some .NET applications only. You may have problems with pressing WPF button (maybe QT button is clickable - not checked), but in such case code like app.DialogTitle.wait('ready').set_focus(); app.DialogTitle.type_keys('{ENTER}') may help. Your case is quite simple and probably some tricks with pywinauto are enough. Is your "app with popup" 64-bit or 32-bit?
wait and wait_not functions have timeout parameter. But if you need precisely listener with potentially infinite loop awaiting popups, good direction is global Windows hooks (pyHook can listen mouse and keybd events, but cannot listen dialog opening). I'll try to find my prototype that can detect new windows. It uses UI Automation API event handlers... and... ops... it requires IronPython. I still don't know how to set UI Automation handler with COM interface from standard CPython.
EDIT (2019, January): new module win32hooks was implemented in pywinauto a while ago. Example of usage is here: examples/hook_and_listen.py.

Configure pointer focus properties of Matlab's command window

I'm running Matlab 2013a, under Linux, using Xmonad (using the XMonad.Config.Xfce package).
This problem occurs whether the command window is docked or not.
The command window prompt does not get the keyboard focus unless the pointer is located
over the command window.
Is there a way to get the Matlab command window to have focus behaviour just like other normal windows, like a terminal?
Most important: I'd like to have the keyboard focus follow the window focus,
and not require any special positioning of the pointer, so that I can just "Alt-Tab" around my windows and have the command window get the keyboard focus. All of the resources I've found so far relate to programmatic control of focus; I'm just trying to improve my user experience in an interactive session.
To get keyboard focus on the Command Window, include the following in your xmonad.hs
import XMonad.Hooks.SetWMName
import XMonad.Hooks.ManageHelpers
and configure your ManageHook as follows
myManageHook = composeAll . concat $
[ [appName =? a --> doCenterFloat | a <- myFloatAS ]
, (your other hooks)
] where
myFloatAS = ["MATLAB"]
Finally, include setWMName "LG3D" in your startupHook. See here for a full xmonad.hs configuration which uses this (this is where I found the solution). If you have other Java apps that don't get focus as they should you can add them to the myFloatAS list.
It's a problem in the built-in java.
If i run:
export MATLAB_JAVA=/usr/lib/jvm/java-7-openjdk/jre
matlab -desktop
Matlab works as expected.
I ran into this problem, running MATLAB2014a. I set up setWMName "LG3D" but still i couldn't get focus on my window. I had to click on the focused window to get the cursor, and sometimes the situation was even worse and I had to click on random places till i get my cursor back. This wouldn't happen on MATLAB2010. What worked for me was to use the native version of java as describe above.
In the end, i used the following bash script to start matlab8:
#!/bin/bash
export MATLAB_JAVA=/usr/lib/jvm/java-7-openjdk-amd64/jre/
/usr/local/bin/matlab8 -desktop -nosplash