Writing pressed key to variable
조회 수: 50 (최근 30일)
이전 댓글 표시
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
채택된 답변
Stephen23
2021년 10월 17일
편집: Stephen23
2021년 10월 17일
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
Stephen23
2021년 10월 18일
편집: Stephen23
2021년 10월 18일
" 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.
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!