MATLAB: Pause program and await keypress

后端 未结 6 1818
旧巷少年郎
旧巷少年郎 2021-02-09 07:11

I am writing a program in which at some point a graph is plotted and displayed on screen. The user then needs to press \'y\' or \'n\' to accept or reject the graph. My current s

相关标签:
6条回答
  • 2021-02-09 07:34

    You don't want to use waitforbuttonpress since it locks the figure gui (no zooming, panning etc).

    pause can cause the command window to steal the focus from the figure.

    The solution I find to work best is to open the figure with a null keyPressFcn in order to avoid focus problems:

    figure('KeyPressFcn',@(obj,evt) 0);
    

    and then wait for CurrentCharacter property change:

    waitfor(gcf,'CurrentCharacter');
    curChar=uint8(get(gcf,'CurrentCharacter'));
    
    0 讨论(0)
  • 2021-02-09 07:42

    The waitforbuttonpress command is good but is triggered by either a mouse click or a key press. If you want it to trigger only from a key press, you can use the following hack:

    while ~waitforbuttonpress
    end
    
    0 讨论(0)
  • 2021-02-09 07:43

    Why not using waitforbuttonpress instead?

    Documentation: http://www.mathworks.fr/help/techdoc/ref/waitforbuttonpress.html

    0 讨论(0)
  • 2021-02-09 07:52

    Wait for buttonpress opens up a figure, which may be unwanted. Use instead

    pause('on');
    pause;
    

    which lets the user pause until a key is pressed.

    0 讨论(0)
  • 2021-02-09 07:54

    Wait for key press or mouse-button click:

    Example:

    w = waitforbuttonpress;
    if w == 0
        disp('Button click')
    else
        disp('Key press')
    end
    

    for more information visit: http://www.mathworks.com/help/matlab/ref/waitforbuttonpress.html

    0 讨论(0)
  • 2021-02-09 07:55

    I'd use the input function:

    a = input('Accept this graph (y/n)? ','s')
    
    if strcmpi(a,'y')
        ...
    else
        ...
    end
    

    Although admittedly it requires two keypresses (y then Enter) rather the one.

    0 讨论(0)
提交回复
热议问题