python - 在python中获取控制台窗口的位置
问题描述
我正在寻找一种快速获取 Python 控制台窗口一角位置的方法。我实际上要检查的是光标位置是否位于控制台内,以及它是否返回相对于控制台的位置。一些代码:
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()
ofos
和win32api
.
解决方案
GetConsoleWindow
可以获取控制台窗口的句柄,然后可以GetWindowRect
用来获取窗口的rect,其中包含左上角的坐标,但是不需要自己检查,可以直接PtInRect
用来检查是否pt 在矩形中,然后调用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")
如果考虑控制台被其他窗口覆盖的情况,即下图中控制台被计算器覆盖的情况,红点在控制台的矩形中,但重点是计算器。
在这种情况下,如果只想返回(-1,-1),可以使用WindowFromPoint
它并与控制台窗口句柄进行比较:
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")
推荐阅读
- sql-server - T-SQL 以正确的顺序查找日期的行
- azure - Azure 函数不会在 Push-OutputBinding 中使用 Stop ErrorAction 引发终止错误
- css - CSS中的多个动画 - 仅重复秒动画
- python - 使用 ANN 进行时间序列预测
- python - pyglet中方法内的形状
- machine-learning - 关于实时更新机器学习模型的问题
- python - 在 Python 中使用 GPIOZero 打开和关闭 OpenCV 窗口
- javascript - Selenium 测试:使用 Webauthn 进行身份验证
- python - 摆脱日志消息中的字符串填充
- python - 如何使用嵌入预测下一个单词