首页 > 解决方案 > 在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()ofoswin32api.

标签: pythonwinapi

解决方案


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")

推荐阅读