MATLAB: Is the string property of the Edit UIControl empty in the KeyPressFcn callback (GUIDE)

controleditemptykeypressfcnMATLABnopropertystringtext;

I have the code below to extract the string from my Edit UIControl in GUIDE:
% --- Executes on key press with focus on edit1
function edit1_KeyPressFcn(hObject, eventdata, handles)
get(hObject, 'string')
However, it always returns an empty character array. Why is this?
The only way I can get the hObject.string property to return anything in the callback is if I place a breakpoint in it.

Best Answer

This issue stems from the way Edit UIControls work in GUIDE. The 'string' property of this object is not modified until either a) the user presses 'enter' or b) the user switches focus away from the Edit box (placing a breakpoint caused the focus to switch to the MATLAB Command Window, which is why you are only seeing the 'string' property update only with the breakpoint).
If you need this property to update without hitting 'enter' or switching focus, the best way to work around this is to use the 'eventdata' argument to the 'KeyPressFcn'. From 'eventdata', you can extract the key that was pressed and add it to a persistent character array.
First, create the string in the CreateFcn for your Edit control:
handles.searchString = '';
guidata(hObject, handles);
Second, add the following code to the front of your KeyPressFcn:
% --- Executes on key press with focus on edit1
function edit1_KeyPressFcn(hObject, eventdata, handles)
% if backspace, delete last character in the search string
if strcmp(eventdata.Key, 'backspace')
handles.searchString(end) = [];
guidata(hObject, handles);
% else, add the key that was pressed to the search string
else
keyPressed = eventdata.Character;
handles.searchString = [handles.searchString keyPressed]
guidata(hObject, handles);
end
handles.searchString
% your code goes here