[英]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.