pythonwinapi

Get position of console window in python


I am looking for a quick way to get the position of one corner of the Python console window. What I'm actually trying is to check is whether the cursor position lays within the console and if it does return the position relative to the console. Some code:

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

I have looked at the dir() of os and the win32api.


Solution

  • GetConsoleWindow can get the handle of the console window, and then you can use GetWindowRect to get the rect of the window, which includes the coordinates of the upper left corner, but you don’t need to check by yourself, you can directly use PtInRect to check if the pt is in the rect, and then call ScreenToClient to convert screen coordinate to client coordinate of 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")
    

    If you consider the case where the console is covered by other windows, that is, the console is covered by the calculator in the figure below, the red dot is in the rect of the console, but it is focused on the calculator. enter image description here In this case, if you only want to return (-1,-1), You can use WindowFromPoint and compare it with the console window handle:

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