Skip to content

Instantly share code, notes, and snippets.

@jl2
Created July 14, 2011 20:04
Show Gist options
  • Save jl2/1083319 to your computer and use it in GitHub Desktop.
Save jl2/1083319 to your computer and use it in GitHub Desktop.
Launch a windows process on a background desktop so any windows it creates are invisible.
#!/usr/bin/env python3
# Launch an application on a new desktop
# The motivation for this is another script that runs depends.exe in profiling mode.
# When depends.exe profiles the application the application's windows pop-up and get
# in the way. It's really annoying, hence spawndesk.py
import sys
import random
import win32con
import win32event
import pywintypes
import win32process
import win32service
def quoteArg(arg):
if arg.find(' ')>=0:
return '"' + arg + '"'
else:
return arg
def main(args):
# Boiler plate security attributes required by CreateDesktop()
sa = pywintypes.SECURITY_ATTRIBUTES()
sa.bInheritHandle=1
# Random 8 character desktop name
randomName = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 8))
# Create the new desktop
hdesk=win32service.CreateDesktop(randomName, 0, win32con.MAXIMUM_ALLOWED, sa)
# StartupInfo structure that goes to the new desktop
si=win32process.STARTUPINFO()
si.lpDesktop=randomName
# Convert ['test.exe', 'with space', 'nospace'] to 'test.exe "with space" nospace'
cmdLine = ' '.join(map(quoteArg, args))
try:
# Launch the process
prc_info=win32process.CreateProcess(None, cmdLine,None,None,True,win32con.CREATE_NEW_CONSOLE,None,'.',si)
# Wait for it
win32event.WaitForSingleObject(prc_info[0], -1)
except Exception as e:
print(e)
# Cleanup
hdesk.CloseDesktop()
if __name__=='__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment