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

66 次查看(过去 30 天)
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 个评论
raym
raym 2017-3-24
Is the reason that the WindowButtonMotionFcn only monitor the movement of mouse inside the figure?

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2017-3-24
编辑:Guillaume 2017-3-24
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 个评论
Guillaume
Guillaume 2017-3-24
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);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by