Using a keypress to activate a button
9 次查看(过去 30 天)
显示 更早的评论
I have seen several posts on this topic but I am a Matlab novice and am still having trouble. I have a larger program that currently uses pushbuttons for responses but I am modifying it for children and want them to also be able to push a key.
I am using Matlab Version 7.0.4.365 (R14) Service Pack 2.
As a start I used guide to create a simple GUI with a single pushbutton. When I use the mouse to click on the pushbutton it changes the figure color in a random way. I then copied the pushbutton callback that guide created e.g., jnk('pushbutton1_Callback',gcbo,[],guidata(gcbo)) and pasted that into the keypressfcn section of the figure using the property editor. My thought was that I would be able to now use any key or the mouse to activate the button code.
This works great IF I only use the keys to activate the button. Any key works. However, once I use the mouse to press the button the keys no longer work (except for the spacebar for some reason).
Because of the task I want to be able to use both the mouse click and, if possible, keypresses during a single run so the current setup isn't useful (i.e., only use the keypress).
I also tried creating a separate function to call using keypressfcn but that did the same thing.
Any suggestions would be greatly appreciated.
Thanks,
Ben
0 个评论
回答(2 个)
Jan
2012-3-27
If a button is activated with the mouse, it gets the focus. Subsequent keyboard events are forwarded to the button's keypress functions in consequence.
To solve this problem, the figure must get the focus inside the callbacks of the button. Actually figure(gcf) should do this, but this does not work since Matlab 5.3. A workaround is to disable the button temporarily inside its callback:
set(ButtonH, 'Enable', 'off');
drawnow;
set(ButtonH, 'Enable', 'on');
Using the WindowsKeyPressFcn works in modern Matlab versions only.
Jia Tsing Ng
2014-5-30
编辑:Jia Tsing Ng
2014-5-30
I've tried this and using Jan Simon's suggestion of
set(ButtonH, 'Enable', 'off');
drawnow;
set(ButtonH, 'Enable', 'on');
at the end of the button callback function works! THANKS A LOT!
I initially tried copying the assigning a button's KeyPressFcn to the same KeyPressFcn for the figure. This works as well, but is dangerous especially if you have (as I did!) a 'spacebar' shortcut. Pressing the space button will activate whatever button that is in focus, then do what your space shortcut is.
So I'd still recommend Jan's suggestion. Although there SHOULD be something more straightforward. Anybody from Mathworks reading this?!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Migrate GUIDE Apps 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!