【问题标题】:How to use KeyPressFCN in matlab with a function already create?如何在已创建函数的matlab中使用KeyPressFCN?
【发布时间】:2013-05-17 15:50:27
【问题描述】:

我正在寻找信息。 我和其他像我一样的学生必须在 Matlab 中创建声音。我们创建它们,我们还必须创建一个交互接口来播放这些声音。

所以我们创建了一架钢琴,当我们点击一​​个琴键时,它就会发出声音(这就是功能。)

我们还希望我们可以按下键盘上的一个键来调用该函数。我们听说过 KeyPressFCN,但我们不知道如何使用它,因为当我们搜索每个教程时,他们没有提供足够的信息。

那么,当我们右键单击我们想要的元素时,我们称之为 KeyPressFCN,下一步是什么?我们必须做些什么才能将函数“放置”到这个 KeyPressFCN 上。

例如,要发出一种声音,我们有:

% --- Execution lors d'un appui sur le bouton Do (première blanche)
function pushbutton1_Callback(hObject, eventdata, handles)
octave = str2double(get(handles.zone1,'String'));
frequence = 2093; %--- Fréquence initialement Do6
frequence2 = frequence./ octave;
son = sin(2*pi*frequence2*(0:0.000125:0.2));
sound(son);

【问题讨论】:

    标签: matlab matlab-guide


    【解决方案1】:

    其实我只是在引用 Matlab 文档和帮助。

    1. 如果您使用GUIDE右键单击您的图形(不是任何对象)>>查看回调>> KeyPressFcn,那么它将自动生成以下函数:

      function figure1_KeyPressFcn(hObject, eventdata, handles)
      % hObject    handle to figure1 (see GCBO)
      % eventdata  structure with the following fields (see FIGURE)
      %   Key: name of the key that was pressed, in lower case
      %   Character: character interpretation of the key(s) that was pressed
      %   Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
      % handles    structure with handles and user data (see GUIDATA)
      
      % add this part as an experiment and see what happens!
      eventdata % Let's see the KeyPress event data
      disp(eventdata.Key) % Let's display the key, for fun!
      

      玩弄你的键盘并查看事件数据。显然,当您键入时,该图形必须处于活动状态。

    2. 如果您使用的是 uicontrol(而不是 GUIDE),这是制作 gui 的编程方式

      (使用内联函数)

      fig_h = figure; % Open the figure and put the figure handle in fig_h
      set(fig_h,'KeyPressFcn',@(fig_obj,eventDat) disp(['You just pressed: ' eventDat.Key])); 
      % or again use the whole eventDat.Character or eventDat.Modifier if you want.
      
    3. 或者如果你不想使用内联函数:

      fig_h = figure;
      set(fig_h,'KeyPressFcn', @key_pressed_fcn);
      

      然后定义你的key_pressed_fcn,如:(创建一个新的mfile,名称为:key_pressed_fcn.m,当然你可以使用任何你想要的名称,但与上面的KeyPressFcn名称相同)

      function key_pressed_fcn(fig_obj,eventDat)
      
      get(fig_obj, 'CurrentKey')
      get(fig_obj, 'CurrentCharacter')
      get(fig_obj, 'CurrentModifier')
      
      % or 
      
      disp(eventDat)
      
    4. 或者!使用脚本作为 KeyPressFcn 回调函数

      fig_h = figure;
      set(fig_h,'KeyPressFcn', 'key_pressed');
      

      然后编写key_pressed脚本:

      get(fig_h, 'CurrentKey')
      get(fig_h, 'CurrentCharacter')
      get(fig_h, 'CurrentModifier')
      

    Matlab 帮助参考“KeyPressFcn 事件结构”在: http://www.mathworks.com/help/matlab/ref/figure_props.html

    【讨论】:

    • 考虑解决方案#2:如何在主程序中按下按键?我的意思是,如果一个脚本创建了一个图形,它如何对刚刚按下的键做出反应?,如何检查eventDat.Key的值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2010-12-26
    相关资源
    最近更新 更多