[4] | 1 | function ch = getkey(m) |
---|
| 2 | |
---|
| 3 | % GETKEY - get a single keypress |
---|
| 4 | % CH = GETKEY waits for a keypress and returns the ASCII code. Accepts |
---|
| 5 | % all ascii characters, including backspace (8), space (32), enter (13), |
---|
| 6 | % etc, that can be typed on the keyboard. CH is a double. |
---|
| 7 | % |
---|
| 8 | % CH = GETKEY('non-ascii') uses non-documented matlab 6.5 features to |
---|
| 9 | % return a string describing the key pressed so keys like ctrl, alt, tab |
---|
| 10 | % etc. can also be used. CH is a string. |
---|
| 11 | % |
---|
| 12 | % This function is kind of a workaround for getch in C. It uses a modal, but |
---|
| 13 | % non-visible window, which does show up in the taskbar. |
---|
| 14 | % C-language keywords: KBHIT, KEYPRESS, GETKEY, GETCH |
---|
| 15 | % |
---|
| 16 | % Examples: |
---|
| 17 | % |
---|
| 18 | % fprintf('\nPress any key: ') ; |
---|
| 19 | % ch = getkey ; |
---|
| 20 | % fprintf('%c\n',ch) ; |
---|
| 21 | % |
---|
| 22 | % fprintf('\nPress the Ctrl-key: ') ; |
---|
| 23 | % if strcmp(getkey('non-ascii'),'control'), |
---|
| 24 | % fprintf('OK\n') ; |
---|
| 25 | % else |
---|
| 26 | % fprintf(' ... wrong key ...\n') ; |
---|
| 27 | % end |
---|
| 28 | % |
---|
| 29 | % See also INPUT, CHAR |
---|
| 30 | |
---|
| 31 | % (c) 2005 Jos |
---|
| 32 | % email jos @ jasen .nl |
---|
| 33 | % Feel free to (ab)use, modify or change this contribution |
---|
| 34 | |
---|
| 35 | |
---|
| 36 | % Determine the callback string to use |
---|
| 37 | if nargin == 1, |
---|
| 38 | if strcmp(lower(m),'non-ascii'), |
---|
| 39 | callstr = ['set(gcbf,''Userdata'',get(gcbf,''Currentkey'')) ; uiresume '] ; |
---|
| 40 | else |
---|
| 41 | error('Argument should be the string ''non-ascii''') ; |
---|
| 42 | end |
---|
| 43 | else |
---|
| 44 | callstr = ['set(gcbf,''Userdata'',double(get(gcbf,''Currentcharacter''))) ; uiresume '] ; |
---|
| 45 | end |
---|
| 46 | |
---|
| 47 | % Set up the figure |
---|
| 48 | % May be the position property should be individually tweaked to avoid visibility |
---|
| 49 | fh = figure('keypressfcn',callstr, ... |
---|
| 50 | 'windowstyle','modal',... |
---|
| 51 | 'position',[0 0 1 1],... |
---|
| 52 | 'Name','GETKEY', ... |
---|
| 53 | 'userdata','timeout') ; |
---|
| 54 | try |
---|
| 55 | % Wait for something to happen |
---|
| 56 | uiwait ; |
---|
| 57 | ch = get(fh,'Userdata') ; |
---|
| 58 | catch |
---|
| 59 | % Something went wrong, return and empty matrix. |
---|
| 60 | ch = [] ; |
---|
| 61 | end |
---|
| 62 | close(fh) ; |
---|