Hi,
I want to write a code which detect left and right arrow stroke in keyboard.
I tried to use below kind of code but it shows crosshair and also interrupts the working of other line. (Making crosshair invisible is somewhat important in this case)
[~,~,button]=ginput(1);
switch button
case 28 %left
case 29 %right
end
Is there any better way to do it? Thanks!

 採用された回答

Nirav Sharda
Nirav Sharda 2017 年 4 月 18 日

7 投票

There are a couple of ways to achieve this. You can use the KeyPressFcn callback on the figure window. Here is an example.
h_fig = figure;
set(h_fig,'KeyPressFcn',@myfun);
The myfun here could have something like this.
function myfun(src,event)
disp(event.Key);
end
The other way to achieve this is to use ' waitforbuttonpress ' function. Here is an example code.
k = waitforbuttonpress;
% 28 leftarrow
% 29 rightarrow
% 30 uparrow
% 31 downarrow
value = double(get(gcf,'CurrentCharacter'))
I hope this helps.

6 件のコメント

M Min
M Min 2017 年 4 月 18 日
Thanks! The last one works fine!
Austin Susa
Austin Susa 2018 年 10 月 19 日
I'm just commenting here so I can find this again. I've figured out how to make a button press affect another variable but I'm not good at making multiple things run at once. Also, Matlab keeps crashing. Pretty sure my laptop needs more RAM and that's the cause though. I'll probably just split my code into multiple Matlab files so I can test each part separately then figure out how to put them together later.
Austin Susa
Austin Susa 2018 年 10 月 19 日
Also, which numbers go along with the W and S keys
Mathieu Möller
Mathieu Möller 2018 年 11 月 20 日
w is 119 and s is 115.
Joseph Rucker
Joseph Rucker 2020 年 4 月 20 日
How do you find out what the numbers for the keys are?
Caden Scharpf
Caden Scharpf 2020 年 4 月 21 日
The numbers for the keys are their corresponding ASCII Charactershttps://www.petefreitag.com/cheatsheets/ascii-codes/

サインインしてコメントする。

その他の回答 (2 件)

balandong
balandong 2020 年 3 月 23 日

0 投票

Maybe Im bit late to join the party. But you can consider this FEX submission KbTimer. It is MEX base thus quite fast

カテゴリ

ヘルプ センター および File ExchangeDisplay Image についてさらに検索

質問済み:

2017 年 4 月 16 日

回答済み:

2023 年 10 月 19 日

Community Treasure Hunt

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

Start Hunting!