title: How to run python program in background to keep active window the same
body: <p>I have written a program that will change the foreground window to 85% of the monitor's dimensions and to run successfully the foreground window needs to remain the same.</p>
  
  <p>I have put the python script (.pyw) into a batch file (running pythonw) and created a shortcut to the batch file on the desktop with a shortcut to run it quickly. I also made it run the batch file minimized but it still switches the foreground window to the minimized command prompt.</p>
  
  <p>Per the python code below I am using pywin32 for the window manipulation. I get the information for the monitor because I have a three monitor setup so need to take into account the coordinates of the appropriate monitor.</p>
  
  <pre class="lang-py prettyprint-override"><code>#! python
  
  import win32api
  import win32gui
  import win32con
  
  monitors = win32api.EnumDisplayMonitors()
  monitorsDict = {}
  hwnd = win32gui.GetForegroundWindow()
  currentWindowDimensions = win32gui.GetWindowRect(hwnd)
  monitorInFocus = str(win32api.MonitorFromWindow(hwnd))
  
  for i in range(len(monitors)):
      monitorsDict[str(monitors[i][0])] = monitors[i][2]
  
  maxWidth = (monitorsDict[monitorInFocus][2]-monitorsDict[monitorInFocus][0]) * .85
  maxHeight = (monitorsDict[monitorInFocus][3]-monitorsDict[monitorInFocus][1]) * .85
  x = int(currentWindowDimensions[0])
  y = int(currentWindowDimensions[1])
  newWidth = int(maxWidth + x)
  newHeight = int(maxHeight + y)
  newDimensions = (x, y, newWidth, newHeight)
  
  win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, x, y, newWidth, newHeight, 0)
  </code></pre>
  
  <p>The batch file is below:</p>
  
  <pre><code>C:\path\to\pythonw\executable\pythonw.exe C:\path\to\pyw\script\WindowSizing.pyw
  </code></pre>
  
  <p>I was under the impression that if I run pythonw rather than python it would run the script in the background without opening a command prompt window but this does not appear to be happening. Because the command prompt is the foreground window the script changes the size of the command prompt window and then closes it resulting in no change to the window I wanted to resize.</p>
  
  <p>Is there something in the pywin32 module that would allow me to get the handle for the previous foreground window? Alternatively, is there a way to run the python script silently so the foreground window does not change?</p>