Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get other running processes window sizes in Python

This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.

like image 749
Brian Paden Avatar asked Sep 30 '08 05:09

Brian Paden


3 Answers

Using hints from WindowMover article and Nattee Niparnan's blog post I managed to create this:

import win32con
import win32gui

def isRealWindow(hWnd):
    '''Return True iff given window is a real Windows application window.'''
    if not win32gui.IsWindowVisible(hWnd):
        return False
    if win32gui.GetParent(hWnd) != 0:
        return False
    hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0
    lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)
    if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)
      or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):
        if win32gui.GetWindowText(hWnd):
            return True
    return False

def getWindowSizes():
    '''
    Return a list of tuples (handler, (width, height)) for each real window.
    '''
    def callback(hWnd, windows):
        if not isRealWindow(hWnd):
            return
        rect = win32gui.GetWindowRect(hWnd)
        windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1])))
    windows = []
    win32gui.EnumWindows(callback, windows)
    return windows

for win in getWindowSizes():
    print win

You need the Win32 Extensions for Python module for this to work.

EDIT: I discovered that GetWindowRect gives more correct results than GetClientRect. Source has been updated.

like image 188
DzinX Avatar answered Sep 30 '22 16:09

DzinX


I'm a big fan of AutoIt. They have a COM version which allows you to use most of their functions from Python.

import win32com.client
oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" )

oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title

width = oAutoItX.WinGetClientSizeWidth("Firefox")
height = oAutoItX.WinGetClientSizeHeight("Firefox")

print width, height
like image 42
Dustin Wyatt Avatar answered Sep 30 '22 16:09

Dustin Wyatt


Check out the win32gui module in the Windows extensions for Python. It may provide some of the functionality you're looking for.

like image 20
Swaroop C H Avatar answered Sep 30 '22 14:09

Swaroop C H