How do I force my GUI to give focus to a specific UICONTROL?

26 views (last 30 days)
I would like to be able to programmatically set the focus of my GUI to a specific uicontrol. For example, I would like to be able to give focus to a specific editable text box, so that the user is set up for entering text in it when the GUI starts. This would also be useful for making specific fields active after previous fields are entered and executed by hitting the "Enter" key, or setting a specific pushbutton as the default option when creating a custom GUI dialog.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Apr 2023
Edited: MathWorks Support Team on 19 Apr 2023
This feature has been added in MATLAB 7.0 (R14) which has the UICONTROL function that can give focus to a uicontrol object. The following code can serve as an example of this:
% create some uicontrols
u(1) = uicontrol('Style','edit');
u(2) = uicontrol('Style','pushbutton','Position',[20 60 60 20]);
% set focus to the edit text box
uicontrol(u(1))
If you are using UIWAIT or WAITFOR, you need to ensure that the figure has focus before setting the UICONTROL:
set(gcf,'Visible','on');
drawnow;
uicontrol(u(1))
If you are using a previous version, read the following:
The ability to force your GUI to give focus to a specific UICONTROL is not available in MATLAB 6.5.1 (R13sp1) or earlier.
Currently, to work around this issue, try downloading the "setfocus" function from the File Exchange.
NOTE: These files are not fully tested and not officially supported by MathWorks.
One known problem with this function is that it is not compilable into a standalone application. If you try to compile it, it will have no effect on your compiled application.
Note also that this function is not supported on other platforms than Windows.
1. Download the submission from the File Exchange
and place it in any of your own directories that are in your MATLAB path.
2. Restart MATLAB
3. After restarting MATLAB, issue the following command at the MATLAB prompt :
rehash toolboxcache

More Answers (0)

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!