getkey

버전 2.1 (2.8 KB) 작성자: Jos (10584)
Get a keypress
다운로드 수: 20.1K
업데이트 날짜: 2019/2/11

라이선스 보기

편집자 메모: This file was selected as MATLAB Central Pick of the Week

CH = getkey waits for a single keypress and returns the ASCII code. It
accepts all ascii characters, including backspace (8), space (32),
enter (13), etc, that can be typed on the keyboard.
Non-ascii keys (ctrl, alt, ..) return a NaN. CH is a double.

CH = getkey(N) waits for N keypresses and returns their ASCII codes.
getkey(1) is the same as getkey without arguments.

getkey('non-ascii') or getkey(N, 'non-ascii') uses non-documented
matlab features to return a string describing the key pressed.
In this way, keys like ctrl, alt, tab etc. can also distinguished.
The return is a string (when N = 1) or a cell array of strings.

[CH, T] = getkey(...) also returns the time between the start of the
function and each keypress. This is, however, not very accurate.

This function is kind of a workaround for "getch" in C. It uses a modal,
but non-visible window, which does show up in the taskbar.
C-language keywords: KBHIT, KEYPRESS, getkey, GETCH

Example 1 - get a single ascii key
fprintf('\nPress any key: ') ;
ch = getkey ;
fprintf('%c\n',ch) ;

Example 2 - wait for a specific key
fprintf('\nPress the Ctrl-key within 3 presses: ') ;
ch = getkey(3,'non-ascii')
if ismember('control', ch), fprintf('OK\n') ;
else fprintf(' ... wrong keys ...\n') ; end

Example 3 - Typing game
S = 'abcdefghjiklm' ;
fprintf('Type "%s" as fast as possible ...\n', S) ;
[C, T] = getkey(numel(S)) ;
C = char(C) ; T = T(end)-T(1) ;
if ~isequal(S, C), fprintf('OOPS!!! ') ; end
fprintf('You typed "%s" in %.2f seconds.\n', C, T) ;

See also input, uiwait
getkeywait (file Exchange)

Author's note: after 14 years still going strong ;-)

인용 양식

Jos (10584) (2024). getkey (https://www.mathworks.com/matlabcentral/fileexchange/7465-getkey), MATLAB Central File Exchange. 검색 날짜: .

MATLAB 릴리스 호환 정보
개발 환경: R2018b
모든 릴리스와 호환
플랫폼 호환성
Windows macOS Linux
카테고리
Help CenterMATLAB Answers에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!
버전 게시됨 릴리스 정보
2.1

modernised & added typing game example

1.3.0.0

Update 2.0 (june 2012): ability to get multiple keypresses

1.2.0.0

changed some figure properties; added check of figure existence

1.1.0.0

tested for newer releases

1.0.0.0

updated lay-out