MATLAB: How to make a push button respond to clicking with the right mouse button

contextMATLABmenupushbuttonrightclick

I have created a push button in my GUI. I would like to have some action occur when I right-click on the push button.

Best Answer

There are two properties which can be used in conjunction to accomplish this.
One is the button's 'ButtonDownFcn' callback function. This callback function executes when pressing a mouse button on or near a UICONTROL object -- including when pressing the right mouse button.
The other property is the figure's 'SelectionType' property. This property indicates which kind of click was registered in the figure window -- including clicks on controls within the figure.
Putting these two together, you can define a 'ButtonDownFcn' callback for a push button which checks the figure's 'SelectionType' property to detect a right-click. An example is shown below. (In that example, the ANCESTOR function is used to get the figure's handle. If this is being done in a GUIDE-created GUI, this is unnecessary as the 'handles' structure already provides access to the figure's handle.)
function test
uicontrol('Style', 'pushbutton', ...
'ButtonDownFcn', @myCallback);
end
function myCallback(src, evt)
figHandle = ancestor(src, 'figure');
clickType = get(figHandle, 'SelectionType');
if strcmp(clickType, 'alt')
disp('right click action goes here!');
end
end