9

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.

1
  • My use case is I open up several camera windows with chrome, and I'd like to have a program to automatically find them and tile them for me on one of my monitors.
    – RufusVS
    Jun 20, 2022 at 16:27

5 Answers 5

13

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.

3
  • 1
    +1 for providing your original sources. I always enjoy finding out what other people are reading. Oct 1, 2008 at 0:11
  • Any suggestions on how to do it under linux (preferably gnome)?
    – seler
    May 15, 2012 at 22:10
  • It gives something like (1378864, (677, 522)), how to target an application, for example notepad.exe ?
    – 0x48piraj
    May 28, 2018 at 17:33
10

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
6
  • Does AutoIt over win32com.client have a slightly differing API? Based on AutoIt function reference that applies to COM, oAutoItX.Opt() should be oAutoItX.AutoItSetOption(), and oAutoItX.WinGetClientSizeWidth() and oAutoItX.WinGetClientSizeHeight() should actually be one method/function oAutoItX.WinGetClientSize() that returns a 2 item tuple or list containing the width (1st index) & height (2nd index).
    – David
    Jan 5, 2015 at 7:47
  • 1
    If we're talking AutoIt and Python, there's also a wrapper for it w/o going through win32com directly: github.com/jacexh/pyautoit, see also pypi.python.org/pypi/PyAutoIt/0.3.
    – David
    Jan 5, 2015 at 7:49
  • @David, I answered this 6 1/2 years ago! From the AutoItX Help file for AutoItSetOption: "You may use Opt as an alternative to AutoItSetOption." And there is no WinGetClientSize, just WinGetClientSizeWidth and WinGetClientSideHeight. Are you sure you're looking at the AutoItX documentation? Jan 6, 2015 at 16:49
  • Maybe there's a discrepancy between the CHM help file vs online docs, or there's been a change in later versions of AutoIt? I refer to version 3. Which version does your example refer to? I just checked v3's CHM file and online docs, and there is only WinGetClientSize. See autoitscript.com/autoit3/docs/functions/WinGetClientSize.htm. But you are right about Opt function. I overlooked that alternative alias mentioned in AutoItSetOption: autoitscript.com/autoit3/docs/functions/AutoItSetOption.htm
    – David
    Jan 6, 2015 at 23:23
  • 1
    Those are the docs for AutoIt, not AutoItX. AutoItX is (from help file): "a DLL version of AutoIt v3 that provides a subset of the features of AutoIt via an ActiveX/COM and DLL interface." AutoItX and it's help file is packaged with the main AutoIt download. I am referring to version 3.3.12.0 Jan 7, 2015 at 0:20
2

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

0

I updated the GREAT @DZinX code adding the title/text of the windows:

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)
    text = win32gui.GetWindowText(hWnd)
    windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1]), text ))
windows = []
win32gui.EnumWindows(callback, windows)
return windows

for win in getWindowSizes():
print(win)
0

I Modify someone code ,

This well help to run other application and get PID ,

import win32process
import subprocess
import win32gui
import time 
 
def get_hwnds_for_pid (pid):
  def callback (hwnd, hwnds):
    if win32gui.IsWindowVisible (hwnd) and win32gui.IsWindowEnabled (hwnd):
      _, found_pid = win32process.GetWindowThreadProcessId (hwnd)
      if found_pid == pid:
        hwnds.append (hwnd)
    return True
    
  hwnds = []
  win32gui.EnumWindows (callback, hwnds)
  return hwnds

# This the process I want to get windows size. 
notepad = subprocess.Popen ([r"C:\\Users\\dniwa\\Adb\\scrcpy.exe"]) 
time.sleep (2.0)

while True: 
  for hwnd in get_hwnds_for_pid (notepad.pid):
    rect = win32gui.GetWindowRect(hwnd)
    print(hwnd, "=>", win32gui.GetWindowText (hwnd))

    # You need to test if your resolution really get exactly because mine is doesn't . 
    # I use . 16:9 Monitor , Calculate the percent using this calculations , , (x * .0204082) and (y * .0115774)
    print((hwnd, (rect[2] - rect[0], rect[3] - rect[1])))
    x = rect[2] - rect[0]
    y = rect[3] - rect[1]
    print(type(x), type(y))
    time.sleep(1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.