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 Center および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by