GETKEY - get a single keypress CH = GETKEY waits for a keypress and returns the ASCII code. Accepts all ascii characters, including backspace (8), space (32), enter (13), etc, that can be typed on the keyboard. CH is a double. CH = GETKEY('non-ascii') uses non-documented matlab 6.5 features to return a string describing the key pressed so keys like ctrl, alt, tab etc. can also be used. CH is a string. 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 Examples: fprintf('\nPress any key: ') ; ch = getkey ; fprintf('%c\n',ch) ; fprintf('\nPress the Ctrl-key: ') ; if strcmp(getkey('non-ascii'),'control'), fprintf('OK\n') ; else fprintf(' ... wrong key ...\n') ; end See also INPUT, CHAR
0001 function ch = getkey(m) 0002 0003 % GETKEY - get a single keypress 0004 % CH = GETKEY waits for a keypress and returns the ASCII code. Accepts 0005 % all ascii characters, including backspace (8), space (32), enter (13), 0006 % etc, that can be typed on the keyboard. CH is a double. 0007 % 0008 % CH = GETKEY('non-ascii') uses non-documented matlab 6.5 features to 0009 % return a string describing the key pressed so keys like ctrl, alt, tab 0010 % etc. can also be used. CH is a string. 0011 % 0012 % This function is kind of a workaround for getch in C. It uses a modal, but 0013 % non-visible window, which does show up in the taskbar. 0014 % C-language keywords: KBHIT, KEYPRESS, GETKEY, GETCH 0015 % 0016 % Examples: 0017 % 0018 % fprintf('\nPress any key: ') ; 0019 % ch = getkey ; 0020 % fprintf('%c\n',ch) ; 0021 % 0022 % fprintf('\nPress the Ctrl-key: ') ; 0023 % if strcmp(getkey('non-ascii'),'control'), 0024 % fprintf('OK\n') ; 0025 % else 0026 % fprintf(' ... wrong key ...\n') ; 0027 % end 0028 % 0029 % See also INPUT, CHAR 0030 0031 % (c) 2005 Jos 0032 % email jos @ jasen .nl 0033 % Feel free to (ab)use, modify or change this contribution 0034 0035 0036 % Determine the callback string to use 0037 if nargin == 1, 0038 if strcmp(lower(m),'non-ascii'), 0039 callstr = ['set(gcbf,''Userdata'',get(gcbf,''Currentkey'')) ; uiresume '] ; 0040 else 0041 error('Argument should be the string ''non-ascii''') ; 0042 end 0043 else 0044 callstr = ['set(gcbf,''Userdata'',double(get(gcbf,''Currentcharacter''))) ; uiresume '] ; 0045 end 0046 0047 % Set up the figure 0048 % May be the position property should be individually tweaked to avoid visibility 0049 fh = figure('keypressfcn',callstr, ... 0050 'windowstyle','modal',... 0051 'position',[0 0 1 1],... 0052 'Name','GETKEY', ... 0053 'userdata','timeout') ; 0054 try 0055 % Wait for something to happen 0056 uiwait ; 0057 ch = get(fh,'Userdata') ; 0058 catch 0059 % Something went wrong, return and empty matrix. 0060 ch = [] ; 0061 end 0062 close(fh) ;