【问题标题】:MATLAB: How to run function until the key is released?MATLAB:如何在释放键之前运行函数?
【发布时间】:2015-09-21 18:16:18
【问题描述】:

我有一个 GUI,我想从按下给定键到释放键重复一些过程。

当按键被按下时,我知道如何做一些处理。但是有什么方法可以例如每秒显示随机数,直到释放密钥?

感谢您的回答。 贾贾

【问题讨论】:

    标签: matlab keypress keyrelease


    【解决方案1】:

    您可以将计时器附加到您的人物,以KeyPressFcn 启动它并以KeyReleaseFcn 停止它。

    下面的例子将创建一个图形,只要按下 f 键,就会在控制台中显示一个随机数。

    function h=keypressdemo
    
    h.fig = figure ;
    
    %// set up the timer
    h.t = timer ;
    h.t.Period = 1 ;
    h.t.ExecutionMode = 'fixedRate' ;
    h.t.TimerFcn = @timer_calback ;
    
    %// set up the Key functions
    set( h.fig , 'keyPressFcn'   , @keyPressFcn_calback ) ;
    set( h.fig , 'keyReleaseFcn' , @keyReleaseFcn_calback ) ;
    
    guidata( h.fig ,h)
    
    function timer_calback(~,~)
        disp( rand(1) )
    
    function keyPressFcn_calback(hobj,evt)
        if strcmp(evt.Key,'f')
            h = guidata(hobj) ;
            %// necessary to check if the timer is already running
            %// otherwise the automatic key repetition tries to start
            %// the timer multiple time, which produces an error
            if strcmp(h.t.Running,'off')
                start(h.t)
            end
        end
    
    function keyReleaseFcn_calback(hobj,evt)
        if strcmp(evt.Key,'f')
            h = guidata(hobj) ;
            stop(h.t)
        end
    

    这是一个简单的计时器模式,回调函数所用的时间比间隔时间少很多,所以在这里没有问题。如果您希望任何函数在完成后立即重新执行(一种无限循环),您可以通过更改计时器的executionmode 来设置它(阅读timer 文档以获取示例。
    但是,请注意,如果您的回调永久执行并消耗所有(matlab 唯一)线程资源,您的 GUI 可能会变得反应迟钝。

    【讨论】:

    • 嗨!我为我们创建了一个 MATLAB 聊天室,以防您想讨论与 MATLAB 相关的任何题外话,或者如果您想讨论跨度超过 cmets 块的事情。当你有时间时停下来! chat.stackoverflow.com/rooms/81987/matlab
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    相关资源
    最近更新 更多