Writing pressed key to variable

5 views (last 30 days)
Dominik Swider
Dominik Swider on 17 Oct 2021
Edited: Stephen on 18 Oct 2021
I want to pause the execution of my function in order to get input from the user. I would like to do this only when the key 'p' is pressed on the keyboard. I want the output to be 0 when no key is pressed and the respective key when a key is pressed. I already found a way to do it on the internet, however I always get 0 as the output even if a key is pressed. I don't seem to be able to get the variable key outside of the function scope. How can I accomplish this?
function key=pressedKey
set(gcf,'KeyPressFcn', @detectkeystroke);
function key = detectkeystroke(~,event)
global key

Accepted Answer

Stephen on 17 Oct 2021
Edited: Stephen on 17 Oct 2021
I suspect that you are getting synchronous code (e.g. the evaluation of a script or function) mixed up with asynchronous code (e.g. callbacks and events triggered by GUI interactions).
To get the "pressed key" character ultimately means that you are waiting for an event to occur in GUI, which is naturally best processed within the GUI itself (as callbacks are by their very nature designed to work with asynchronous code evaluation). If you want that character returned by the function then you can use WAITFOR to wait until the user closes the figure, and works without error:
>> myout = pressedKey()
myout =
function out = pressedKey()
fgh = figure();
key = 0; % this is a shared variable, so no need for ugly GLOBAL.
set(fgh,'KeyPressFcn', @detectkeystroke);
waitfor(fgh) % wait until figure is closed.
out = key; % shared variables cannot be output variables.
function detectkeystroke(~,event)
Stephen on 18 Oct 2021
" I tried to use your function but the problem is that it pauses the execution of my program everytime pressedKey is called even if no key is pressed"
For the reason that I already explained at the start of my answer.
"Are there other ways to pause the execution only when a certain key is pressed"
Probably you should use the keypress callback to directly pause your program, e.g. by setting a flag.
If you keep thinking in terms of synchronous code (e.g. returning an output argument (which GUI callbacks do not have)) then this task will be very difficult. Once you start to think in terms of asynchronous code and your GUI as whole, then this task will be much easier: callbacks make things happen. In your case, you want to pause something.

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!