Code archives/Miscellaneous/Run program (Windows-only)

This code has been declared by its author to be Public Domain code.

Download source code

Run program (Windows-only) by BlitzSupport2013
This gives a little more control over launching graphical applications on Windows than other methods available, eg. OpenURL, system_, CreateProcess, etc.

(Whether or not the minimise/maximise/hide flags have any effect depends on the program, though most should work correctly; the one I actually intended this for, Google Chrome, basically ignores all of the SW_SHOW parameters!)
?Win32

' See http://msdn.microsoft.com/en-gb/library/windows/desktop/bb762153(v=vs.85).aspx
' for explanation of each constant...

Const SW_HIDE			= 0
Const SW_SHOWNORMAL		= 1
Const SW_SHOWMINIMIZED		= 2
Const SW_SHOWMAXIMIZED		= 3
Const SW_MAXIMIZE		= 3 ' No idea why this duplicate exists...
Const SW_SHOWNOACTIVATE		= 4
Const SW_SHOW			= 5
Const SW_MINIMIZE		= 6
Const SW_SHOWMINNOACTIVE	= 7
Const SW_SHOWNA			= 8
Const SW_RESTORE		= 9
Const SW_SHOWDEFAULT		= 10

Extern "win32"
	Function ShellExecuteA (window:Int, op:Byte Ptr, file:Byte Ptr, params:Byte Ptr, dir:Byte Ptr, show:Int)
End Extern

' RunProgram parameters: exe = path to executable file, params = valid parameters for executable, showflag = one of the above constants, dir = working directory for program

Function RunProgram:Int (exe:String, params:String = "", showflag:Int = SW_SHOWNORMAL, dir:String = "")
	If dir = "" Then dir = ExtractDir (exe)
	Print dir
	If ShellExecuteA (0, "open".ToCString (), exe.ToCString (), params.ToCString (), dir, showflag) > 32
		Return True
	Else
		Return False
	EndIf
End Function
?

' Run one instance maximised, one minimised and one normal...

RunProgram "notepad.exe", "", SW_SHOWMAXIMIZED
Delay 500

RunProgram "notepad.exe", "", SW_SHOWMINIMIZED
Delay 500

RunProgram "notepad.exe"

' You can also run programs "hidden"; if you try this, you'll have to use Task Manager to kill notepad.exe afterwards!

' RunProgram "notepad.exe", "", SW_HIDE

' NB. Notepad is normally in the default Windows path, hence no need to provide the full path in this case; however, most programs will need the full path to the executable.

Comments

Henri2013
Hi,

I'm wondering how would this work when used in "batch mode". For example you have a commandline program that modifies files or creates something according to program parameters and you would use ShellExecute to run this program 1000 times in a row. Would each start as it's own process and then you might run out of resources ? Would there be a way to wait (not freeze program flow) until process ends ?

-Henri


BlitzSupport2014
I only just saw this, sorry! You can force each call to wait until the program exits by amending the code to use ShellExecuteEx. There's a 'no async' flag that can be set to do this.


Henri2014
Better late then never ;-)


Code Archives Forum