MATLAB: In MATLAB R2017a, how to change the focus of the “WindowKeyPressFcn” figure callback function from the command window back to the figure when a key is pressed

MATLAB

In MATLAB R2017a, when setting the "KeyPressFcn" or "WindowKeyPressFcn" from the figure callback function, the figure loses focus and the key pressed is forwarded to the command window.  When the same thing is done in MATLAB R2012a, the figure retains focus and the key pressed is not forwarded to the command window.

Best Answer

This is a known issue, and a potential workaround for this issue in MATLAB R2017a is to create a null figure callback function for "WindowKeyPressFcn" or "KeyPressFcn".
% Example of figure retaining focus when keyboard button is pressed
function KeyPressTest()
f = figure;
f.WindowKeyPressFcn = {@testKeyPressFcn};
end
function testKeyPressFcn(source,~)
disp('Focus Retained')
source.WindowKeyPressFcn = {@testKeyPressFcnNull};
end
function testKeyPressFcnNull(~,~)
end