how can we control push button in matlab gui by keyboard instead of mouse click?

 Accepted Answer

heisenberg - if you are using GUIDE to create your GUI, then you could assign a WindowKeyPressFcn callback to your figure (GUI) and then, based on the key pressed while the figure has focus, you could call the appropriate button.
Suppose that your GUI/figure is named figure1 and you have one push button (named pushbutton1) that you wish to fire when you press the x key. Your callback to capture key presses could look something like
function figure1_WindowKeyPressFcn(hObject, eventdata, handles)
% determine the key that was pressed
keyPressed = eventdata.Key;
if strcmpi(keyPressed,'x')
% set focus to the button
uicontrol(handles.pushbutton1);
% call the callback
pushbutton1_Callback(handles.pushbutton1,[],handles);
end
In the above we check for when the x is pressed and then simulate the pressing of the button by calling the appropriate callback. You may not need to set focus to the button using uicontrol but I don't think that it hurts to do this as well.

5 Comments

thank you Geoff Hayes.It worked. how can I focus all push button at a same time?it works fine for 1 push button.but if i use another push button it doesn't switch the focus..
I don't understand what you mean by how to "focus all push buttons at the same time". Do you want to associate different keys with different buttons? If so, then you can just do extend the above to handle multiple keys. i.e.
if strcmpi(keyPressed,'x')
% set focus to the button
uicontrol(handles.pushbutton1);
% call the callback
pushbutton1_Callback(handles.pushbutton1,[],handles);
elseif strcmpi(keyPressed,'y')
% do something else
elseif strcmpi(keyPressed,'v')
% etc.
end
i used two keypressfcn for 2 push buttons & assigne 2 keys.for 1st pushbutton your program works fine.but for second push button when i give second key input it does not recognize, but if i gave one input from mouse click to 2nd push button it got focused and once it get focused the related assign key starts to works. so i want to ask what should i do to avoid that mouse click to shift the focus.?
i used separate keypressfcn for 2 pushbuttons.
Please post some of your code so that I can get an idea of what you have implemented.

Sign in to comment.

More Answers (2)

when I press a key it just types in the command window and nothing else happens... help

1 Comment

Wajih - please post this as a new question rather than as an answer. Include any relevant code.

Sign in to comment.

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!