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
Send Parameter To CMD
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;
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. –
Tailgate
I invite you to read the documentation about ShellExecute, Armin. There you'll find out about what the fifth parameter is for. –
Tumefaction
I don't know what was the matter but after some tries it works properly. thank you, it was useful help. –
Tailgate
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
© 2022 - 2024 — McMap. All rights reserved.