简体   繁体   中英

AutoHotkey MouseMove not centering properly

I'm running the below code and I expect the mouse to move to the center of the currently active window when I hit comma.....instead it is moving to different points on the screen, depending on where the window is on the screen. It only centers the mouse properly when the window is positioned at the top left (x=0, y=0).

#NoEnv
SendMode Input
#WinActivateForce

Sysget, Mon2, Monitor, 2

,::

WinGetActiveStats, Title, Width, Height, X, Y
 {
MsgBox, The active window "%Title%" is %Width% wide`, %Height% tall`, and positioned at %X%`,%Y%.

;center_x:=X+(Width*.5)
;center_y:=Y+(Height*.5)

MouseMove, X+(Width*.5), Y+(Height*.5), 90

 }
Return

Check out CoordMode in the documentation.

Sets coordinate mode for various commands to be relative to either the active window or the screen.

CoordMode, ToolTip|Pixel|Mouse|Caret|Menu [, Screen|Window|Client]

The default CoordMode is Screen which is why you get two different locations. Set the CoordMode to Window to assure that your mouse centering works on the active window.

You can set it for the entire script by calling it during the Auto-Execute section of the script.

I would be sure that Width and Height are the actual dimensions of the window and not the screen resolution. Then check X and Y to ensure they're the actual top-left corner of the active window.

If the width and height are not from the actual window, ie the screen size, then this is expected behaivor. Perhaps you could show us the calling function to get a better idea of where those parameters are coming from.

the problem was that MousMove uses the coordinates of the window by default, so I changed the MouseMove line to the following:

MouseMove, Width*.5, Height*.5

All is good.

The following script will move mouse to Active Window on dual screen system.

I could not get it to work until I put in the sleep line, WinGetPos was getting info before the window had moved.

~#+right::
~#+left::
    Sleep,1000
    WinGetPos, X, Y, width, height, A
    center_x:=width/2
    center_y:=height/2
    MouseMove,center_x,center_y,
return

Tried it all nothing works. The trick is to use DllCall("SetCursorPos", int, x, int, y) . Here is the code to move mouse to center of window. Works on multi-montior and non-fullscreen windows.

MoveMouseInCenterOfActiveWindow:
CoordMode,Mouse,Screen
WinGetPos, winTopL_x, winTopL_y, width, height, A
;MouseMove, X, Y, 0 ; does not work with multi-monitor (always off)
    winCenter_x := winTopL_x + width/2
    winCenter_y := winTopL_y + height/2
DllCall("SetCursorPos", int, winCenter_x, int, winCenter_y)
Tooltip winTopL_x:%winTopL_x% winTopL_y:%winTopL_y% winCenter_x:%winCenter_x% winCenter_y:%winCenter_y%
return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM