Matlab GUI Tutorial - Adding Keyboard Shortcuts / Hotkeys to a GUI
18 Dec 2007 Quan Quach 14 comments 4,783 views
Writing the Code for the GUI
-
Click on the
icon on the GUI figure to bring up the accompanying .m file. -
The first thing we need to do is to map a function to a keyboard press event. This basically means that whenever any keyboard key is pressed, the designated function is called. Also, we need to define a variable to hold the histogram data. We can accomplish this with the following code, which should be placed in the opening function before the line
guidata(hObject,handles):%create an array of 9 zeroes handles.cats = zeros(1,9); %whenever any key is pressed, myFunction is called set(handles.figure1,'KeyPressFcn',@myFunction) %if we wanted to make it so the function is called when the key is released, %you would use set(handles.figure1,'KeyReleaseFcn',@myFunction) instead
-
Next, we need to define myFunction. Paste the following code into the end of the m-file.
function myFunction(src,evnt) %this function takes in two inputs by default %src is the gui figure %evnt is the keypress information %this line brings the handles structures into the local workspace %now we can use handles.cats in this subfunction! handles = guidata(src); %get the value of the key that was pressed %evnt.Key is the lowercase symbol on the key that was pressed %so even if you tried "shift + 8", evnt.Key will return 8 k=str2num( evnt.Key ); if k >0 & k < 10 axes(handles.axes1); %select the axes to plot on %update the array containing the histogram information handles.cats(k)=handles.cats(k)+1; %create the histogram graph bar(handles.cats); %updates the handles structures! guidata(src, handles); end %if k is zero, terminate the gui and put the data onto a new figure if k==0 %get the position and unit type of the GUI figure guiWindowPosition = get(src,'Position'); guiWindowUnits = get(src,'Units'); close(src); %close the gui finalWindow=figure; %create a new figure %set the position and units of the new figure set(finalWindow,'Units',guiWindowUnits) set(finalWindow,'Position',guiWindowPosition) %populate the new figure with the histogram bar(handles.cats); end
-
Now save and run your GUI, you should see the following appear:

-
Try pressing some keys to verify that it works. When you are finished, press 0 to close the GUI. Once you do this, the GUI will close but a new figure will replace it. At this point any further keyboard input will have no effect on the figure.
- Character - The character displayed as a result of the key(s) released.
- Modifier - This field is a cell array that contains the names of one or
more modifier keys that the user releases (i.e., control, alt, shift, or empty
if no modifier keys were released). On Macintosh computers, MATLAB can also
return command. - Key - The lower case label on key that was released.
-
Lets try another example wherein the GUI will respond when you press “+” or when you press the combination of “control” + “alt + “r”.
-
Cut and paste this code into the beginning of myFunction:
%initialize these variables control = 0; alt = 0; shift = 0; %determine which modifiers have been pressed for x=1:length(evnt.Modifier) switch(evnt.Modifier{x}) case 'control' control = 1; case 'alt' alt = 1; case 'shift' shift = 1; end end %if the following combination is pressed, then the following text %is displayed at the command prompt if (control ==1 && alt==1 && strcmp(evnt.Key,'r')) disp('I just pressed the combination of control, alt, and r!'); end %if this character is pressed on the keyboard, it will display the %following text. Noticed evnt.Character was used, and not evnt.Key! if(strcmp(evnt.Character,'+')); disp('I just pressed the + key!'); end
-
Now, run the GUI again and try to input in “+” and the combination of “control” + “alt” + “r”. You should see the appropriate messages at the Matlab Command Prompt!
An Advanced Example using a Combination of Input Keys
In the previous example, we kept it simple and only used numerical key presses. But most “hotkeys” or “keyboard shortcuts” involve the use of alt, control, or shift. Luckily, Matlab is able to handles these cases as well!
The evnt input parameter from MyFunction is a structure that contains three fields of information. Using this information, we can construct more complex key input combinations.
Passing Additional Input Arguments
You can define the callback function to accept additional input arguments by adding them to the function definition. For example:
function myFunction(src,evnt,arg1,arg2)
When using additional arguments for the callback function, you must set the value of the property to a cell array (i.e., enclose the function handle and arguments in curly braces). For example:
set(handles.figure1,'KeyPressFcn',{@myFunction,arg1,arg2})
For more information you can visit this Matlab link and do an internal search (control + f) for “keyPressFcn”.
This is the end of the tutorial.
Pages: 1 2
14 Responses to “Matlab GUI Tutorial - Adding Keyboard Shortcuts / Hotkeys to a GUI”
Leave a Reply
Include MATLAB code in your comment by doing the following:
<pre lang="MATLAB">
%insert code here
</pre>


Hi, Quan Quach :
Great job you are doing. Very good tutorial this one.
Is there a a time when you will talk about sharing data (using the handles structure, of course) between subfunctions of a GUI that are not in the same file? For example: I have a GUI and on it I call a function in another file. I want my handles structure to be seen whitin this other function.
Also I would ask you if you have in mind a tutorial about how to use the varargout and the handles.output = hObject in a correct way. I’ve always tried to use them but never reached a satisfactory result.
Thanks in advance,
JanKees
JanKees:
You can learn more about sharing data in this tutorial.
I have a bunch of tutorials that I want to write in the near future, and I will certainly try to include one on the topic that you requested. Thanks for commenting and leaving feedback!
hi,
hi,
wish you a happy new year. when you will post the next tutorial man, daily i check thrice. man its been 12 long days. post a simple tutorial atleast since it’s a new year week.
14 days
Happy New Year Subin,
Thank you for showing your support! We apologize for the lack of updates during the holiday season. A lot of back-end work was taking place during this time as we are revamping the design of the site. You won’t be disappointed :-).
But upon your request, a new matlab tutorial will be featured within a day. Thank you for your patience. And again, we welcome all readers to send in tutorial requests through our contact form.
Hi,
Happy new year!
Keep up the good work. The tutorials are short and to the point.
Thanks
Maurice
Hi,
thanks for the very good blog entry!
Hello my friends
Hi, u r doing a great job i must say by helping people regarding matlab. I have started doing matlab and i know nothing about gui implementation. I have been given a project to design piano. I am sure you would have some idea about how to design piano, I need some tutorial on gui implementation of implementing piano in matlab,means whenever i press any key,it gives sound of the frequencies and also gives gui. I require only the gui implementation. Kindly you can mail me a tutorial on this with the code also if possible. Kindly mail me on leo1inmail@gmail.com as soon as possible, I shall b v thankful to u.
Quan Quach
U are doing an interesting job. Thank you
hello..
i have some prolem to design the GUI by using the mathlab..can u help me to solve this problem?
[...] by lokorn on Wed 07-1-2009 [WoW] WoW Emu hacker 2.4.3 / 5.0 Saved by nbqx on Tue 06-1-2009 Comment on Matlab GUI Tutorial - Adding Keyboard Shortcuts … Saved by TheAjentJ on Fri 26-12-2008 Winamp Global Hotkeys… Useful Feature Saved by multani0 on [...]
This looks cool so far, what’s up people?
If it’s not just all bots here, let me know. I’m looking to network
Oh, and yes I’m a real person LOL.
Later,