Writing pressed key to variable
44 views (last 30 days)
Show older comments
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
key=0;
set(gcf,'KeyPressFcn', @detectkeystroke);
function key = detectkeystroke(~,event)
global key
key=event.Key;
end
end
0 Comments
Accepted Answer
Stephen23
on 17 Oct 2021
Edited: Stephen23
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 =
y
Where:
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)
key=event.Key;
end
end
2 Comments
Stephen23
on 18 Oct 2021
Edited: Stephen23
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.
More Answers (0)
See Also
Categories
Find more on Language Fundamentals 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!