Search code examples
matlabmatlab-figurematlab-guide

Check if editbox is active (and evaluate WindowKeyPressFcn only if its not) in matlab


I would like to be able to test whether given edit box (uicontrol with 'style' set to 'edit') is being used at the moment (whether the cursor is inside that box / the edit box has focus).

Unfortunatelly the 'Selected' property of the editbox seems to be 'off' all the time and it's use is discouraged by MathWorks

I am open to Java solutions (but I have not tried any yet).

Background

My broader goal is to activate specific functions in response to keys pressed by the user (keyboard shortcuts) but only if the user is not typing these letters into an edit box.

I evaluate keyboard shortcuts with 'WindowKeyPressFcn' callback. I thought about using editbox's 'KeyPressFcn' callback to block 'WindowKeyPressFcn' (by passing something through setappdata or 'UserData') but it seems that 'WindowKeyPressFcn' is always evaluated first.

So now I'm trying to detect whether the editbox is in use some other way.


Solution

  • Since MATLAB uicontrols have underlying Java Swing GUI controls, I can think of two "Java solutions":

    1. Associate a FocusGainedCallback with the Java object of editbox (using FindJObj - see below) (and possibly other UI elements), and update some handle \ persistent \ global variable from this function to hold the currently focused object handle. This type of callback is mentioned in an UndocumentMatlab article on uicontrol callbacks.

    2. You should be able to use Java'sisFocusOwner() method on the underlying java object of your editbox (this method is mentioned in the Java documentation of the focus subsystem).

    Note: the simplest way to get the java object is using the utility FindJObj that is briefly described here.