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 last one that opens... How can开发者_Python百科 I do it?
I'm using this command
window = win32gui.GetForegroundWindow()
win32gui.MoveWindow(window, 0, 0, 1440, 900, True)
that works perfectly, but only with the focus window... and the second window of firefox witch opens with the script doesnt get focused...
This should work
import win32gui, win32con
hwnd = win32gui.GetForegroundWindow()
win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
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:
import ctypes
user32 = 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 ashWnd
) and how the window should be seen (set as 3 inSW_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:
- no ctypes (which is sometimes worth considering, see the answers to this question)
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
精彩评论