Skip to content Skip to sidebar Skip to footer

How Can I Maximize A Specific Window With Python?

I'm trying to maximize a specific window with python... Here is the deal: I have a script that opens 2 firefox windows (selenium rc), and I need to maximize the second window, the

Solution 1:

This should work

import win32gui, win32conhwnd= win32gui.GetForegroundWindow()
win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)

Solution 2:

If you don't want to install separate modules you could use the inbuilt ctypes module. The usage is not that different from the accepted answer above, except that you interact with the DLLs themselves and don't have to install anything else.

First here is the code:

importctypesuser32= ctypes.WinDLL('user32')

SW_MAXIMISE = 3

hWnd = user32.GetForegroundWindow()

user32.ShowWindow(hWnd, SW_MAXIMISE)

Now the explanation:

  • Get ctypes module.
  • Get the appropriate runtime, for reference use the Windows documentation and look under "Requirements".
  • Set the SW_MAXIMISE value to 3 since this is the value (indicated in the documentation) to set the window to maximum.
  • hWnd = user32.GetForegroundWindow() retrieves the foreground window (the window that is in front of all the others) - see here for the complete description on the function.
  • Use ShowWindow() to control the windows show state. This takes two arguments, the handle to the window (defined above as hWnd) and how the window should be seen (set as 3 in SW_MAXIMISE = 3). You can see the documentation for a more complete list of the various options.

You could of course put this into a function to make it easy to use.


Another approach:

Since in this case there are no worries about being cross platform, you could build a C or C++ extension instead.

Benefits:

Downfalls:

  • needs to be compiled (since it's on Windows only, you only need to worry about compiling for x32 bit and x64 bit)
  • must be a module (i.e. you can't intergrate it in one file)
  • requires a minimum knowlege of either C or C++ as well as the Python api itself

The actual function to be called should not be that difficult:

static PyObject * max_win(PyObject *self, PyObject *args) {
    ShowWindow(GetForegroundWindow(), SW_MAXIMISE);
    return Py_BuildValue(""); // Return nothing
}

Note that this is only a fragment of the actual code needed

Post a Comment for "How Can I Maximize A Specific Window With Python?"