MATLAB: How to programmatically return focus to a figure after pressing F10 which selects the menu bar in MATLAB 7.9 (R2009b)

MATLAB

As part of a GUI, I would like to use the KeyPressFcn callback to determine the keyboard button that is pressed. However, when I press F10, the figure's menu bar is selected and any further key presses are ignored. The following code demonstrates this issue.
function fig_keypress
% function fig_keypress will create a figure and then
% report the key pressed in the command widow.
figure('KeyPressFcn',@cb);
function cb(src,evnt)
evnt.Key
end
end

Best Answer

The ability to programmatically return focus to the figure is not available in MATLAB 7.8 (R2009a). The F10 key in Windows is reserved for activating the menu bar. Once the F10 key is pressed, the Escape key is needed to deselect the menu. One inelegant workaround is to toggle the visibility of the MenuBar as the following example code demonstrates. This has the unfortunate side-effect of causing the figure to flicker, although the focus is returned to the figure as desired so that future key presses are correctly interpreted.
 
function fig_keypress
% function fig_keypress will create a figure and then

% report the key pressed in the command window.

h = figure('KeyPressFcn',@cb);
function cb(src,evnt)
evnt.Key
if strcmpi(evnt.Key,'f10')
% toggle MenuBar visibility
set(h,'MenuBar','none');
set(h,'MenuBar','figure');
end
end
end
If a custom menu bar is being used, another inelegant workaround is to toggle the visibility of the figure and update the figure with the "drawnow" command. This also has the unfortunate side-effect of causing the figure to flicker. 
function fig_keypress
% function fig_keypress will create a figure and then
% report the key pressed in the command window.
h = figure('KeyPressFcn',@cb);
function cb(src,evnt)
evnt.Key
if strcmpi(evnt.Key,'f10')
% toggle Figure visibility
set(h,'Visible','off');
set(h,'Visible','on');
drawnow;
end
end
end