获取应用程序内的光标位置 window 而不是屏幕

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

我试图在应用程序 window(例如记事本)中找到我的鼠标光标 的坐标,但我只能想出位置它在屏幕上。在 python 中有什么方法可以仅在某些 window 内获取光标的 xy 或如何计算屏幕上的位置以在应用程序内定位?我尝试使用 pyautogui、pyautoit 和 pywin32pyautogui.position(), autoit.mouse_get_pos() and win32gui.GetCursorPos()

没有直接的方法可以实现,我think.But你可以考虑换一种方式。

试试下面的代码:

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)