Running Applications From Your Own

Question:
What code do I use for Delphi to run a program and use command line parameters inputted by the user?

Answer:
This code will allow you to launch other applications from your own. To use this function, simply supply a fully qualified path name in ProgramName and any arguments on the command line following the program name separated by a space. As the help file states: “If lpApplicationName is NULL, the first white space-delimited token of the command line specifiesthe module name…” In English, the characters before the first space encountered (or if no space is encountered as in a single program call) is interpreted as the EXE to execute. The rest of the string is the argument line.

procedure ExecNewProcess(ProgramName : String);var  StartInfo  : TStartupInfo;  ProcInfo   : TProcessInformation;  CreateOK   : Boolean;begin  { fill with known state }  FillChar(StartInfo,SizeOf(TStartupInfo),#0);  FillChar(ProcInfo,SizeOf(TProcessInformation),#0);  StartInfo.cb := SizeOf(TStartupInfo);  CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil,False,              CREATE_NEW_PROCESS_GROUP+NORMAL_PRIORITY_CLASS,               nil, nil, StartInfo, ProcInfo);  { check to see if successful }  if CreateOK then    //may or may not be needed. Usually wait for child processes    WaitForSingleObject(ProcInfo.hProcess, INFINITE);end;

For example, let’s say that the user inputted: “/a /b /c” as command line arguments, and you captured them into a string var called “args.” To use ExecNewProcess, you’d simply do this:

MyProgramName := 'C:Program FilesMyProgramMyProgram.EXE';ExecNewProcess(MyProgramName + ' ' + args);

Pretty simple…

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: