How to get the real-time position of mouse outside matlab

66 views (last 30 days)
The function below get the current position of mouse on anywhere of the desktop even outside matlab. As I input
C = get(0, 'PointerLocation')
in command lines and put mouse on other positons before press enter, the ans is the exact position of my mouse even outside matlab.
So next step, I want to let matlab show real-time position of mouse.
function mouseMove (object, eventdata)
C = get(0, 'PointerLocation');
title(gca, ['(X,Y) = (', num2str(1.5*C(1,1)), ', ',num2str(1.5*C(1,2)), ')']);
end
At command line, input:
set (gcf, 'WindowButtonMotionFcn', @mouseMove);
The results is that position only update when mouse was inside the figure. When locate mouse outside the figure(even in matlab window), the number does not update. How to modify this function or is there another function to make it show real-time position of mouse? As I'm not familar with GUI, so it probably that the GUI need improvement. Thanks.
  1 Comment
raym
raym on 24 Mar 2017
Is the reason that the WindowButtonMotionFcn only monitor the movement of mouse inside the figure?

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 24 Mar 2017
Edited: Guillaume on 24 Mar 2017
By default (on Microsoft Windows at least), a window only receive mouse move events when the mouse is within that window. While it is possible for a window to keep receiving mouse move events when the mouse is outside the window, the mechanism for that is not exposed by Matlab (it's very fragile anyway).
Therefore, the only way for you to do what you want is to constantly poll the mouse position. You can be very crude and simply use a while loop, or be a bit more refined and use a timer:
t = timer('ExecutionMode', 'fixedRate', ...
'Period', 0.1, ...
'TasksToExecute', 200, ...
'TimerFcn', @(~,~) fprintf('(X, Y) = (%g, %g)\n', get(0, 'PointerLocation') * 1.5));
start(t); %will display mouse movements for 20 seconds
  5 Comments
Guillaume
Guillaume on 24 Mar 2017
Yes, that works. I would still use a timer, which means that matlab can do other things:
hfig = figure('pos',[100,100,300,300]);
textBox = uicontrol('parent',hfig,'style','text','string','Balance','pos',[40,14,200,90]);
t = timer('ExecutionMode', 'fixedRate', ...
'Period', 0.01, ...
'TimerFcn', @(~,~) set(textBox, 'string', sprintf('(X, Y) = (%g, %g)\n', get(0, 'PointerLocation') * 1.5)));
set(hfig, 'DeleteFcn', @(~,~) stop(t));
start(t);
raym
raym on 25 Mar 2017
It's really cool and fanyastic! Thank you very much!

Sign in to comment.

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!