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

조회 수: 70 (최근 30일)
raym
raym 2017년 3월 24일
댓글: raym 2017년 3월 25일
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);
raym
raym 2017년 3월 25일
It's really cool and fanyastic! Thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (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