MATLAB Answers

How do I find out which uicontrol launched my context menu?

14 views (last 30 days)
Matin on 18 Mar 2013
I have a context menu which I want to use on different edit fields (e.g. 'Reset field to default value'). The Context menu launches a modal dialog which returns an integer.
In the Callback function of the context menu item, how do I find out from which edit field this was launched?
p = get(hObject, 'Parent') % is an uiMenu Item
pp = get(p, 'Parent') % is the complete figure
Regards, Matin

Answers (1)

Jan on 19 Mar 2013
Edited: Jan on 19 Mar 2013
To find the object belonging to a context menu, the CurrentObject can be stored in the Callback of the context menu:
FigH = figure;
ButtonH = uicontrol();
CMH = uicontextmenu('Parent', FigH, 'Callback', {@myRaiseFcn, FigH});
MenuH = uimenu(CMH, 'Label', 'Change color', 'Callback', @myCallback);
set(ButtonH, 'UIContextMenu', CMH);
function myRaiseFcn(CMH, EventData, FigH)
UserData.ClickedObject = get(FigH, 'CurrentObejct'); % The clicked button!
set(CMH, 'UserData', UserData);
function myCallback(MenuH, EventData)
% 1st input is the context menu element, the context menu itself is
% the figure's current object!
CMH = get(MenuH, 'Parent');
UserData = get(CMH, 'UserData');
set(UserData.ClickedObject, 'Color', rand(1, 3));
You can store the handle of the current object inside the Callback of the context menu anywhere else also: By GUIDATA in the figure's ApplicationData, or in the figure's UserData, or in the UserData of the child menu, or globally when the callbacks are nested functions, etc. I think, this information belongs to the ContextMenu, such that storing it there is a fair strategy.


Community Treasure Hunt

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

Start Hunting!