Page 1 of 1

Possible to make mouse coordinates relative to window?

Posted: Thu May 14, 2009 8:35 pm
by Sgraffite
Is there a way to make mouse coordinates relative to the game window, so 0,0 would be the top left corner of the game window? AutoIt had a mode that was relative to the window in focus like that, and that what I found most useful.

I know I could calculate roughly where I want the mouse to be, but when the operating system is running resolutions of different aspect ratios it gets goofy.

Re: Possible to make mouse coordinates relative to window?

Posted: Thu May 14, 2009 9:27 pm
by Administrator
Yes, there is. Through simple math, too.

First, we need to get the position of the window. This is the position of the client region (the actual usable part of the window; does not include title bar and such) as is offset from your screen.

Code: Select all

local win = findWindow("MyWindow");
local wx,wy = windowRect(win);
We will need to update wx and wy each frame. Keep this in mind. This is so that if you move the window, it won't be using old position values and throwing your mouse off.

Now, we can use setMouse() to position the mouse at 0,0 in the client region of our specific window.

Code: Select all

setMouse(wx + 0, wy + 0);
Notice I am adding 0, but it doesn't really do anything. It is not necessary since we're going to 0,0, but if we wanted, say, 10, 20, we can replace the 0s with 10 and 20.

In reverse, we can get the position of the mouse inside our window as well.

Code: Select all

local mx,my = mouseGetPos();
mx = wx - mx;
my = wy - my;

-- mx and my are now the position of the mouse inside our window.
If we just want to use the 'on top' window at all times, we can use foregroundWindow().

Code: Select all

local wx,wy = windowRect(foregroundWindow());
mouseSet(wx + 10, wy + 20); -- forcefully set to 10,20 in the window that's on top

Re: Possible to make mouse coordinates relative to window?

Posted: Thu May 14, 2009 9:56 pm
by Sgraffite
Awesome, ty!