Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect the mouse position anywhere on the screen?

I'm working in MATLAB and I want to get the cursor position from anywhere on the screen.

I would like to continuously get the position of the cursor while the mouse is moving. However, I found that MATLAB can get the mouse position while the mouse is moving only in a GUI.

How can I achieve the same thing but not in a GUI in MATLAB?

like image 898
user3813611 Avatar asked Mar 18 '23 10:03

user3813611


1 Answers

Are you sure MATLAB can only get the mouse co-ordinates within a GUI? It's actually quite simple to get the position of your mouse anywhere on your screen, independent of a GUI.

Use the following:

get(0, 'PointerLocation')

Try this by moving your mouse around and invoking this command each time. You will see that the output keeps changing when the mouse moves. You'll see that this works independent of a GUI.

The output of this function will return a two-element array where the first element is the x or column position and the second element is the y or row position of your mouse. Bear in mind that the reference point is with respect to the bottom left corner of your screen. As such, placing your mouse at the bottom left corner of the screen should yield (1,1) while placing your mouse at the top right corner of the screen yields the resolution of your screen.

Now, if you want to continuously get the position of the mouse, consider placing this call in a while loop while pausing for a small amount of time so you don't overload the CPU. Therefore, do something like this:

while condition
    loc = get(0, 'PointerLocation');

    %// Do something
    %...
    %...

    pause(0.01); %// Pause for 0.01 ms
end
like image 158
rayryeng Avatar answered Apr 27 '23 00:04

rayryeng