Windows - Popen with wShowWindow in startupinfo no

2019-04-09 19:20发布

问题:

I'm trying to do something simple like get calc.exe to start minimized, but it's not happening.

import subprocess
import win32gui
import win32con

info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = win32con.SW_SHOWMINIMIZED
x = subprocess.Popen("calc.exe", startupinfo = info)

It pops up the same as always, no matter what I provide for wShowWindow.

回答1:

I think you've already figured this out, but for the benefit of other readers here's my take:

The problem has something to do specifically with the calc.exe program, not Python nor your code. To prove it, try launching "notepad.exe" (or "wordpad.exe") and it will work -- also note you may need to supply the full path to the target .exe file depending on where it is.

Specifically what is wrong, is according to the STARTUPINFO structure, the wShowWindow member:

For GUI processes, the first time ShowWindow is called, its nCmdShow parameter is ignored wShowWindow specifies the default value. In subsequent calls to ShowWindow, the wShowWindow member is used if the nCmdShow parameter of ShowWindow is set to SW_SHOWDEFAULT.

So what this means is, the first time a program starts, and calls ShowWindow(), it completely ignores whatever you have passed in for wShowWindow in the STARTUPINFO structure. Then, upon another call to ShowWindow(), it will only use your provided value for wShowWindow if the program calls ShowWindow() with its nCmdShow parameter set to SW_SHOWDEFAULT.

So, it seems to be impossible to hide a GUI window if the program itself provides its own value for nCmdShow in ShowWindow(), so it just seems like trial and error to see which programs do that, such as notepad.exe allows you to hide it, while calc.exe you cannot.