8

How can i send parameters to CMD? for example send a path and start it from that path? How can i execute CMD commands? Thanks

Armin Taghavizad
  • 1,625
  • 7
  • 35
  • 57

2 Answers2

10

To start cmd.exe and immediately execute a command, use the /K flag:

procedure TForm1.FormCreate(Sender: TObject);
begin
  ShellExecute(Handle, nil, 'cmd.exe', '/K cd C:\WINDOWS', nil, SW_SHOWNORMAL);
end;

To run a command in cmd.exe and then immediately close the console window, use the /C flag:

procedure TForm1.FormCreate(Sender: TObject);
begin
  ShellExecute(Handle, nil, 'cmd.exe', '/C del myfile.txt', nil, SW_SHOWNORMAL);
end;
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • Thanks for your help but there is a little problem, when i use this: ShellExecute(Handle, nil, 'cmd.exe', '/K cd C:\WINDOWS', nil, SW_SHOWNORMAL); cmd will execute but not at my entered path, it starts from where i saved my project. – Armin Taghavizad Aug 18 '10 at 19:56
  • 4
    I invite you to read the [documentation about ShellExecute](http://msdn.microsoft.com/en-us/library/bb762153.aspx), Armin. There you'll find out about what the fifth parameter is for. – Rob Kennedy Aug 18 '10 at 19:59
  • I don't know what was the matter but after some tries it works properly. thank you, it was useful help. – Armin Taghavizad Aug 18 '10 at 20:32
2

You can also use the Process class - see an example below

AProcess := TProcess.Create(nil); // Create process
AProcess.Executable := 'cmd';                             // Executable to run
AProcess.Parameters.Add('/T:B0');                         // Set background colour
AProcess.Parameters.Add('/K');                            // Keep open

AProcess.Parameters.Add('title');                         // A title for cmd
AProcess.Parameters.Add('My Console');                    // Title
AProcess.Parameters.Add('&&');                            // Start a new command line
AProcess.Parameters.Add('cd');                            // Change directory
AProcess.Parameters.Add('D:\X\');                        // Path to Folder

 {Set environment variable}
AProcess.Parameters.Add('&&');                            // Start a new command line
AProcess.Parameters.Add('HOME='+MYSQL_DIR);                // Set env example

AProcess.Parameters.Add('&&');                            // Start a new command line
AProcess.Parameters.Add('mysql.exe');                     // run mysql.exe
AProcess.Parameters.Add('--host=' + VAR_HOST);          // Parameter server
AProcess.Parameters.Add('--port=' + VAR_PORT); // Parameter mysql server port

AProcess.Execute; // execute detatched process command window remains visible
AProcess.Free;    // free memory        
PodTech.io
  • 4,874
  • 41
  • 24