[英]Get position of console window in python
我正在寻找一种快速的方法来获取 Python 控制台 window 一个角落的 position。 我实际上要检查的是 cursor position 是否位于控制台内,如果它确实返回 position 相对于控制台。 一些代码:
def getCursorPos(windowWidth, windowHeight):
import win32api # pip install pywin32
cursor_x, cursor_y = win32api.GetCursorPos() # Gets cursor position
console_x, console_y = GET_UPPER_LEFT_CORNER_OF_CONSOLE() # Function I'm searching for
if 0 < cursor_x - console_x < windowWidth and 0 < cursor_y - console_y < windowHeight: # Checks if cursor on top of console
return cursor_x - console_x, cursor_y - console_y # Returns cursor position in the actual console
return (-1, -1) # Returns False if cursor outside of console
我看过dir()
的os
和win32api
。
GetConsoleWindow
可以获取控制台window的句柄,然后可以使用GetWindowRect
获取window的rect,其中包含左上角的坐标,但是不需要自己查,直接使用PtInRect
检查 pt 是否在 rect 中,然后调用ScreenToClient
将屏幕坐标转换为hwnd
的客户端坐标。
import win32api
import win32console
import win32gui
def getRelativePos():
pt = win32api.GetCursorPos() #get current cursor pos
hwnd = win32console.GetConsoleWindow() #get console window handle
rect = win32gui.GetWindowRect(hwnd) #get screen coordinate rect of the console window
IsIn = win32gui.PtInRect(rect,pt) # check if the pt is in the rect
if IsIn:
return win32gui.ScreenToClient(hwnd,pt) #convert screen coordinate to client coordinate of hwnd.
else:
return (-1,-1)
print(getRelativePos())
print("Hello World")
如果考虑控制台被其他 windows 覆盖的情况,即下图中的控制台被计算器覆盖,红点在控制台的正方,但重点是计算器。 这种情况下,如果只想返回(-1,-1),可以使用
WindowFromPoint
,与控制台window句柄对比:
import win32api
import win32console
import win32gui
def getRelativePos():
pt = win32api.GetCursorPos() #get current cursor pos
hwnd1 = win32console.GetConsoleWindow() #get console window handle
hwnd2 = win32gui.WindowFromPoint(pt) #get screen coordinate rect of the console window
if hwnd1 == hwnd2:
return win32gui.ScreenToClient(hwnd1,pt) #convert screen coordinate to client coordinate of hwnd.
else:
return (-1,-1)
print(getRelativePos())
print("Hello World")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.