Karol Rostkowski
Karol Rostkowski

Reputation: 21

Getting cursor position inside of an application window instead of the screen

I'm trying to locate coordinates of my mouse cursor inside of an application window(ex. notepad) but all I can come up with is the position of it on the screen. Is there any way in python to get the xy of the cursor only inside certain window or how to calculate the pos on screen to pos inside an app?? I tried using pyautogui, pyautoit and pywin32pyautogui.position(), autoit.mouse_get_pos() and win32gui.GetCursorPos()

Upvotes: 0

Views: 2208

Answers (1)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

There is no direct way to achieve that I think.But you could consider it in another way. enter image description here

Try code below:

import win32gui

the_window_hwnd = win32gui.GetForegroundWindow()  # hwnd of the specific window, it could be whatever you what
left_top_x, left_top_y, *useless_position = win32gui.GetWindowRect(the_window_hwnd) # get the position of window you gave.

mouse_pos_x, mouse_pos_y = win32gui.GetCursorPos()
pos_in_window_x, pos_in_window_y = (mouse_pos_x - left_top_x), (mouse_pos_y - left_top_y)

print(pos_in_window_x, pos_in_window_y)

Upvotes: 2

Related Questions