Introduction

Matlab Logo This tutorial will teach you how to map a keyboard press to execute a GUI callback. We will start with a basic adder GUI. Originally, the GUI adds the two numbers together when the user clicks on the “add” button. We will modify the GUI so that the two numbers will add when the user presses the “enter” key. For more information on this topic, visit this post on Adding Shortcut keys / Hot keys to a GUI.

Adder GUI

Example: Modifying the Adder GUI

  1. First, download the Adder GUI source files here.

  2. Next, we want to add the following line in the opening function:

    %we must define the KeyPressFcn for the edit text boxes or else the
    %enter key will not register while the edit text box is active
     
    set(handles.figure1,'KeyPressFcn',@myFunction); 
    set(handles.input1_editText,'KeyPressFcn',@myFunction);
    set(handles.input2_editText,'KeyPressFcn',@myFunction);
  3. Next, we want to add the following code at the end of the m-file

    function myFunction(src,evnt)
    %keyPressFcn automatically takes in two inputs
    %src is the object that was active when the keypress occurred
    %evnt stores the data for the key pressed
     
    %brings in the handles structure in to the function
    handles = guidata(src);
     
    k= evnt.Key; %k is the key that is pressed
     
    if strcmp(k,'return') %if enter was pressed
        pause(0.01) %allows time to update
     
        %define hObject as the object of the callback that we are going to use
        %in this case, we are mapping the enter key to the add_pushbutton
        %therefore, we define hObject as the add pushbutton
        %this is done mostly as an error precaution
        hObject = handles.add_pushbutton; 
     
        %call the add pushbutton callback.  
        %the middle argument is not used for this callback
        add_pushbutton_Callback(hObject, [], handles);
    end
  4. And that’s it. Run the GUI and verifies that it works.

Download: Source Files

You can download the source files here.

This is the end of the tutorial.