1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
Запуск новой копии интерпретатора команд Windows XP. CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF] [[/S] [/C | /K] строка] /C Выполнение указанной команды (строки) с последующим завершением. /K Выполнение указанной команды (строки) без последующего завершения. /S Изменение поведения после /C или /K (см. ниже) /Q Отключение режима вывода команд на экран (ECHO). /D Отключение выполнения команд AutoRun из реестра (см. ниже) /A Вывод результатов выполнения команд в формате ANSI. /U Вывод результатов выполнения команд в формате UNICODE. /T:цв Выбор цвета текста/фона (более подробно см. COLOR /?) /E:ON Разрешение расширений команд (см. ниже) /E:OFF Запрет расширений команд (см. ниже) /F:ON Разрешение символов завершения имен файлов и папок (см. ниже) /F:OFF Запрет символов завершения имен файлов и папок (см. ниже) /V:ON Разрешение отложенного расширения переменных среды с применением символа '!' в качестве разделителя. Например, /V:ON разрешает использовать !var! в качестве расширения переменной var во время выполнения. Синтаксис var служит для расширения переменных при вводе, что приводит к совсем другим результатам внутри цикла FOR. /V:OFF Запрет отложенного расширения переменных среды. Чтобы указать в одной строке несколько команд, следует разделить их символами '&&' и заключить в кавычки. Кроме того, из соображений совместимости, /X означает то же, что и /E:ON, /Y то же, что и /E:OFF и /R то же, что и /C. Все прочие ключи командной строки игнорируются. Если указаны ключи /C или /K, то остальная часть командной строки после такого ключа обрабатывается как командная строка, а обработка символов кавычек (") ведется по следующим правилам: 1. Если выполняются все перечисленные ниже условия, то символы кавычек в командной строке сохраняются: - ключ /S отсутствует - есть ровно два символа кавычек - между ними нет других специальных символов, как то: &<>()@^| - между ними имеются один или несколько пробелов - строка, заключенная в кавычки, является именем исполнимого файла. 2. В противном случае, проверяется первый символ, и если он является символом кавычек, то он удаляется, также удаляется последний символ кавычек в командной строке, а весь текст после этого последнего символа кавычек сохраняется. Если ключ /D НЕ УКАЗАН в командной строке, то при запуске CMD.EXE выполняется проверка значений переменных REG_SZ или REG_EXPAND_SZ для следующих разделов системного реестра: HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun и/или HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun и если одна из них или обе они присутствуют, то сначала выполняются они. По умолчанию расширенная обработка команд включена. Чтобы запретить расширенную обработку для конкретного вызова, используется ключ /E:OFF Можно включить или отключить расширенную обработку команд для всех вызовов CMD.EXE на данном компьютере или для данного пользователя, с помощью REGEDT32.EXE задав значения REG_DWORD в системном реестре для следующих разделов: HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions и/или HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions равными 0x1 или 0x0. Параметры пользователя перекрывают параметры компьютера. Ключи командной строки, в свою очередь, перекрывают параметры реестра. При расширенной обработке команд изменения и/или добавления затрагивают следующие команды: DEL или ERASE COLOR CD или CHDIR MD или MKDIR PROMPT PUSHD POPD SET SETLOCAL ENDLOCAL IF FOR CALL SHIFT GOTO START (изменен также вызов внешних команд) ASSOC FTYPE Для получения более подробных сведений введите "имяКоманды /?". Отложенное расширение переменных среды НЕ ВКЛЮЧЕНО по умолчанию. Можно включить или отключить отложенное расширение переменных среды для конкретного вызова CMD.EXE с помощью ключей /V:ON или /V:OFF. Можно включить или отключить отложенное расширение переменных среды для всех вызовов CMD.EXE на данном компьютере или для данного пользователя, с помощью REGEDT32.EXE задав значения REG_DWORD в системном реестре для следующих разделов: HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\DelayedExpansion и/или HKEY_CURRENT_USER\Software\Microsoft\Command Processor\DelayedExpansion равными 0x1 или 0x0. Параметры пользователя перекрывают параметры компьютера. Ключи командной строки, в свою очередь, перекрывают параметры реестра. Если отложенное расширение переменных среды включено, то символ '!' (восклицательный знак) может использоваться для замены текущего значения переменной среды во время выполнения. Завершение имен файлов и папок НЕ ВКЛЮЧЕНО по умолчанию. Можно включить или отключить завершение имен файлов и папок для конкретного вызова CMD.EXE с помощью ключей /F:ON или /F:OFF. Можно включить или отключить отложенное расширение переменных среды для всех вызовов CMD.EXE на данном компьютере или для данного пользователя, с помощью REGEDT32.EXE задав значения REG_DWORD в системном реестре для следующих разделов: HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar и/или HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar установив их шестнадцатеричные значения равными коду управляющего символа, используемого для конкретной функции (например, 0x4 для Ctrl-D или 0x6 для Ctrl-F). Параметры пользователя перекрывают параметры компьютера. Ключи командной строки, в свою очередь, перекрывают параметры реестра. Если завершение включено с помощью ключа командной строки /F:ON, то используются два управляющих символа: Ctrl-D для имен папок и Ctrl-F для имен файлов. Чтобы отключить конкретный символ завершения в системном реестре, в качестве кода специального символа используется шестнадцатеричное значение символа пробела (0x20). Завершение вызывается при вводе одного из этих двух специальных символов. Функция завершения берет строку пути слева от точки ввода, дописывает к ней символ шаблона, если таковой отсутствует, а затем строит список путей, которые соответствуют полученному определению. После этого выводится первый элемент этого списка соответствующих путей. Если же список пуст, то подается звуковой сигнал и ничего не выводится. После этого повторный ввод того же самого специального символа приводит к циклическому перебору всех соответствующих путей. Нажатие клавиши <Shift> при вводе управляющего символа позволяет просматривать список путей в обратном порядке. Если изменить выведенный путь, а затем снова ввести управляющий символ, сохраненный список очищается и строится новый список путей. То же самое происходит, если переключиться с одного символа завершения на другой. Единственное отличие при использовании символа завершения файла состоит в том, что при этом для построения списка соответствия берется и путь, и имя файла, а при использовании символа завершения папки берется только путь. Если символ завершения используется в одной из встроенных команд манипулирования папками (CD, MD или RD), то всегда подразумевается символ завершения папок. Символ завершения правильно работает и с именами файлов, содержащими пробелы или иные специальные символы, если при этом строка соответствия заключена в кавычки. Кроме того, если сместить точку ввода влево, а затем использовать символ завершения внутри строки, оставшийся справа от точки ввода текст будет отброшен. Специальные символы, которые требуют обязательного заключения в кавычки: <пробел> &()[]{}^=;!'+,`~ |
To run a cmd command in Delphi, you can follow these steps:
- Import the ShellAPI unit in your Delphi project. This unit provides access to the Shell API (Application Programming Interface) functions.
- Declare a variable of type TStartupInfo and TProcessInformation. These structures will be used to start a new process.
- Use the CreateProcess function from the ShellAPI unit to create a new process. This function takes parameters such as the application name (in this case, «cmd.exe»), the command line parameters (your cmd command), and additional process creation options.
Here’s an example code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
uses ShellAPI; procedure RunCmdCommand(const ACommand: string); var StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin ZeroMemory(@StartupInfo, SizeOf(StartupInfo)); StartupInfo.cb := SizeOf(StartupInfo); // Create the process CreateProcess(nil, PChar('cmd.exe /c ' + ACommand), nil, nil, False, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo); // Wait for the process to finish WaitForSingleObject(ProcessInfo.hProcess, INFINITE); // Close process and thread handles CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); end; |
In this example, the RunCmdCommand
procedure takes the desired cmd command as input and executes it. The /c
parameter is used to specify that the cmd command should be carried out and then the cmd window should close.
To run a cmd command, simply call the RunCmdCommand
procedure and provide the desired cmd command as a string parameter, like this:
1 2 3 |
begin RunCmdCommand('ping www.example.com'); end; |
This will execute the command ping www.example.com
in a separate command prompt window, and the Delphi program will wait for the command execution to complete before continuing.
Best Delphi Books to Read in 2024
1
Rating is 5 out of 5
Delphi Cookbook: Recipes to master Delphi for IoT integrations, cross-platform, mobile and server-side development, 3rd Edition
2
Rating is 4.9 out of 5
Delphi Programming for Dummies
3
Rating is 4.8 out of 5
The Little Book Of Delphi Programming: Learn To Program with Object Pascal (Little Programming Books)
4
Rating is 4.7 out of 5
Delphi GUI Programming with FireMonkey: Unleash the full potential of the FMX framework to build exciting cross-platform apps with Embarcadero Delphi
5
Rating is 4.6 out of 5
Borland Delphi Second Edition
6
Rating is 4.5 out of 5
Mastering Delphi Programming: A Complete Reference Guide: Learn all about building fast, scalable, and high performing applications with Delphi
7
Rating is 4.4 out of 5
Borland Delphi 7
8
Rating is 4.3 out of 5
Delphi High Performance: Master the art of concurrency, parallel programming, and memory management to build fast Delphi apps, 2nd Edition
How to get a list of connected devices using cmd in Delphi?
To get a list of connected devices using the command prompt (CMD) in Delphi, you can use the Windows Management Instrumentation Command-line (WMIC) utility. Here’s an example of how you can achieve this:
- Create a new Delphi project and add a button to the form.
- In the button click event handler, write the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
procedure TForm1.Button1Click(Sender: TObject); var AProcess: TProcess; Output: TStringList; begin AProcess := TProcess.Create(nil); Output := TStringList.Create; try AProcess.Executable := 'wmic'; AProcess.Parameters.Add('path'); AProcess.Parameters.Add('win32_pnpentity'); AProcess.Parameters.Add('get'); AProcess.Parameters.Add('caption, description'); AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes]; AProcess.ShowWindow := swoHIDE; AProcess.Execute; Output.LoadFromStream(AProcess.Output); // Print the output to a memo or any other control Memo1.Lines.AddStrings(Output); finally Output.Free; AProcess.Free; end; end; |
- Add a TMemo control to your form (named as Memo1 in the code above) where the output will be displayed.
- Run the application and click on the button. The connected devices along with their captions and descriptions will be displayed in the memo control.
This code snippet executes the wmic path win32_pnpentity get caption, description
command using the TProcess
component and captures the output in a TStringList
. You can then display the list in any control of your choice, such as a memo, listbox, or grid.
How to pause the execution of a Delphi application until a cmd command finishes running?
You can use the TProcess
class in Delphi to execute a cmd command and wait for it to finish before resuming the execution of your application.
Here is an example of how you can achieve that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
uses System.SysUtils, System.Classes, Winapi.Windows, Winapi.ShellAPI, Vcl.Forms; procedure RunCmdAndWait(const ACommand: string); var ProcessInfo: TProcessInformation; StartupInfo: TStartupInfo; begin FillChar(StartupInfo, SizeOf(TStartupInfo), 0); StartupInfo.cb := SizeOf(TStartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := SW_HIDE; if CreateProcess(nil, PChar('cmd.exe /c ' + ACommand), nil, nil, False, CREATE_NO_WINDOW, nil, nil, StartupInfo, ProcessInfo) then begin WaitForSingleObject(ProcessInfo.hProcess, INFINITE); CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); end; end; procedure TForm1.Button1Click(Sender: TObject); begin // Run a cmd command and wait for it to finish RunCmdAndWait('ping www.google.com'); // Code here will only execute after the cmd command finishes ShowMessage('Command finished executing.'); end; |
In this example, the RunCmdAndWait
procedure uses the CreateProcess
function with the STARTF_USESHOWWINDOW
flag to execute the cmd command. It then uses WaitForSingleObject
to pause the Delphi application execution until the cmd command finishes running. After the command finishes, you can continue executing the rest of your code.
Note that the RunCmdAndWait
procedure uses SW_HIDE
to hide the cmd window. You can change it to SW_SHOWDEFAULT
if you want to show the cmd window during the command execution.
Also, make sure to include the Winapi.Windows
, Winapi.ShellAPI
, and Vcl.Forms
units in your uses
clause.
How to cancel or terminate a running cmd command in Delphi?
To cancel or terminate a running cmd command in Delphi, you can make use of the TProcess component. Here’s an example of how you can achieve it:
- Add a TButton and a TProcess component to your form.
- Double-click on the TButton to create an OnClick event handler.
- In the OnClick event handler, write the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
procedure TForm1.Button1Click(Sender: TObject); begin // Set the command to run in the cmd process Process1.CommandLine := 'ping 127.0.0.1'; // Start the cmd process Process1.Execute; // Sleep for a few seconds to allow the process to start Sleep(5000); // Terminate the process if it is still running if Process1.Running then begin Process1.Terminate; ShowMessage('Process terminated'); end; end; |
In this example, we set the Commandline property of the TProcess component to the cmd command we want to run, which is the ‘ping 127.0.0.1’ command. We then execute the process using the Execute method.
After a few seconds (in this case, 5000 milliseconds), we check if the process is still running using the Running property of the TProcess component. If the process is still running, we terminate it using the Terminate method and display a message indicating that the process has been terminated.
Please note that you may need to adjust the sleep time depending on the duration of the cmd command you are running.
How to pass parameters with a cmd command in Delphi?
To pass parameters with a cmd command in Delphi, you can make use of the ShellExecute
function from the ShellAPI
unit. Here’s an example:
1 2 3 4 5 6 7 |
uses ShellAPI; procedure RunCmdCommand(const Command: string; const Parameters: string); begin ShellExecute(0, 'open', 'cmd.exe', PChar('/C ' + Command + ' ' + Parameters), nil, SW_SHOW); end; |
In the above example, the RunCmdCommand
procedure accepts two parameters: the Command
which represents the command you want to execute and the Parameters
which represents the parameters you want to pass with the command.
To run a specific command with parameters, you can call the RunCmdCommand
procedure and pass the desired command and parameters. For example:
1
|
RunCmdCommand('ping', 'example.com -n 5'); // Executes "ping example.com -n 5" in the cmd
|
Note: The example assumes that ShellAPI
unit is already included in your Delphi project.
What is the command to enable/disable a network adapter using cmd in Delphi?
To enable/disable a network adapter using CMD in Delphi, you can make use of the netsh
command-line utility. The following code demonstrates how to enable and disable a network adapter using CMD in Delphi:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
uses ShellAPI; procedure EnableDisableNetworkAdapter(AdapterName: string; Enable: Boolean); var Command, Parameters: string; begin if Enable then Parameters := 'interface set interface "' + AdapterName + '" admin=enable' else Parameters := 'interface set interface "' + AdapterName + '" admin=disable'; Command := 'netsh ' + Parameters; ShellExecute(0, 'open', 'cmd.exe', PChar('/c ' + Command), nil, SW_HIDE); end; |
To use this function, you can call it like this:
1
|
EnableDisableNetworkAdapter('Local Area Connection', True); // Enable network adapter
|
Replace 'Local Area Connection'
with the name of the network adapter you want to enable/disable. Set the second parameter (Enable
) to True
to enable the adapter or False
to disable it.
Execute CMD command-line programs with Delphi and DOSCommand.
Background
When requiring a command –line program in your Application, setting up
‘createprocess ‘ and pipes is not that difficult. But it would be important to
multithread your code so that your application is not stalled while your
command-line application is running.
Save yourself the trouble as it is easier to use ‘DosCommand’. Straight out, it
is not a simple to use component as it looks?
Free Component
The TurboPack DOSCommand Component Information in
Github indicates the following:-
This Component lets you execute a Dos program (exe, com or batch) and catch the
output in order to put it in a memo. It states that the result should come back
line by line.
You can download the Component from Github or through the GETIT Manager.
Limited examples can be found in the source Header and are a little outdated and
lacking explanation.
Example App
Here is an Example App set up with code that calls various exe(s) such as
ipconfig etc. The code is available to download.
The Component
On reflection, the Component has been well written largely for Win32 and
recently converted to Unicode and includes 64bit for VCL and FMX.
DosCommand is a multithreaded application comprising the following Classes:-
TProcessTimer — to stop the process after XXX seconds and cannot be accessed
externally.
TInputLines — used to synchronise the ‘inputlines’ from main thread with
‘TDosThread’.
TSyncString — synchronises ‘TReadPipe’ and ‘TDosThread’.
TReadPipe — awaits for the pipe input then writes the pipe input to the
‘Tsynchstring ‘the event is then set and ’TDosthread’ then reads the input.
TDosthread — This thread awaits outputs through the pipe.
TDosCommand — forms the component which has the following.
public calls:-
Create;
Destroy;
Execute; // the user call this to execute the command
SendLine// add a line in the input pipe
Stop; // the user can stop the process with this method, stops process and
waits
EndStatus; (esStop, // stopped via ‘TDoscommand.Stop’
esProcess, // ended via Child-Process
esStill_Active, // still active
esNone, // not executed yet
esError, // ended via Exception
esTime); // ended because of time
ExitCode;
IsRunning; // When true, a command is still running
Lines; // if the user want to access all the outputs of a process, lines are
deleted before execution
OutputLines; // can be lines of a memo.
Priority; // stops process and waits, only for ‘createprocess’
ProcessInformation; // ‘Processinformation’ from ‘createprocess’
CommandLine; // command to execute
CurrentDir; // ‘currentdir’ for’childproces’s. if empty then ‘currentdir’ is
same as parent ‘currentdir’.
Environment; // add Environment variables to process .if empty then
environment of parent process is used)
InputToOutput: // check it if you want that the inputs appear also in the
outputs
MaxTimeAfterBeginning;
MaxTimeAfterLastOutput;
OnCharDecoding;
OnCharEncoding; // Events to convert ‘buf’ to ‘Unicodestring’ and reverse !!
not needed if console of child uses AnsiString!! This event is not threadsafe
and no need to change during execution
OnExecuteError; // event if ‘DosCommand.execute’ is aborted via Exception
OnNewChar; // event for each New char that is received through the pipe
OnNewLine; // event for each New line that is received through the pipe
OnTerminated; // event for the ‘endofprocess’, normally, time out or by
‘DosCommand.Stop’ action.
OnTerminateProcess; // event to ask for ‘processtermination’.
What functions don’t Work
I could not get results from the following functions:- ‘Lines’, ‘Outputlines’
and ‘Environment(strings)’ as it resulted in error outputs.
Extra Functions
Working with char decoding/encoding with on ‘newchar’ allows you to work with
individual chars to process. I did not find the need to work with these
functions unless extracting individual char outputs.
Making DosCommand Work
The easiest is to drop the DOScommand component, button and a memo on your form.
Start the code to check if DOScommand is running in the background. This will
ensure that if you happen to rerun the process will not send error messages.
if DosCommand1.IsRunning then
DosCommand1.Stop;
The source states that the timer will stop the process at the
‘maxtimeafterbeginning’ set time. However setting the default = 0 results in the
process not starting or ending.
The source code ‘TThreadtimer’ requires a value > 0 to process. I found that
with slower win32 cpu’s that ‘maxtimeafterOutput = 30’ was the best fit for
mixing 32bit and 64bit. Add the following code.
DosCommand1.InputtoOutput := false;
DosCommand1.MaxTimeAfterBeginning := 1;
DosCommand1.MaxTimeAfterLastOutput := 30;// Value = 1 for a fast win64 multicore
processor
(* you can type the directory directly*)
DosCommand1.CommandLine := GetEnvironmentVariable(‘COMSPEC’); // opens the
CMD.exe
Execute the code to open the CMD.exe in the applications folderpath.
DosCommand1.Execute;
Further processes are made with sendline……
The Boolean portion of Sendline works as follows:-
-
True creates a ‘ ’ (space) before the string.
-
false creates a _ (Lowercasespace) before the string.
DosCommand1.SendLine(‘C:\Windows\System32\ ipconfig’, true); // will open the
ipconfig.exe
DosCommand1.SendLine(», true); // equivalent to pressing the enter key
To capture the processes to a memo use ‘dosCommandNewline’ procedure as
follows:-
procedure TForm4.DosCommand1NewLine(ASender: TObject; const ANewLine: string;
AOutputType: TOutputType);
begin
AOutputType:=otEntireLine;
memo1.Lines.Add(ANewline); //Outputs the lines of the CMD.EXE
end;
To process after the exe has completed, use ‘dosCommandTerminated’ procedure.
This ‘onterminate’ function is the only way to know if the multithreaded process
has stopped running. This is handy if CMD is running a long running exe. The app
waits till the end before processing more messages. No need to call
‘Application.processmessages’.
procedure TForm4.DosCommand1Terminated(Sender: TObject);
begin
//use this area to do something when the multithreaded process has
completed/terminated
memo1.Lines.Add(‘Completed The Process………..’);
end;
That should get you up and running.
Bayesean Blog www.bayeseanblog.com
Happy Coding
Выполнить команду в командной строке
Выполнить команду в командной строке
Выполнить команду в командной строке function ExecAndWait(const ExeName, Params: string; out ExitCode: Cardinal; Timeout: Cardinal = MaxInt): boolean; var sui: TStartupInfo; pi: TProcessInformation; begin ZeroMemory(@sui, SizeOf(sui)); sui.cb := SizeOf(sui); Win32Check(CreateProcess(PChar(ExeName), PChar(Params), nil, nil, False, 0, nil, nil, sui, pi)); try CloseHandle(pi.hThread); Result := WaitForSingleObject(pi.hProcess, Timeout) = WAIT_OBJECT_0; if Result then Win32Check(GetExitCodeProcess(pi.hProcess, ExitCode)); finally CloseHandle(pi.hProcess); end; end; procedure ExecCommandLine(const Cmd: string); var Dummy: Cardinal; begin ExecAndWait(GetEnvironmentVariable('ComSpec'), '/C ' + Cmd, Dummy); end; Пример procedure TForm1.Button1Click(Sender: TObject); begin ExecCommandLine('rd /S /Q "c:\test"'); // удаляем папку c:\test со всеми подпапками end;
Эта запись была добавлена
в Воскресенье, 25 мая, 2008 — 10:16 В разделы Win API, Запуск программ.
Вы можете подписаться на получение новых комментариев RSS 2.0 feed.
Both comments and pings are currently closed.
In Delphi, execute the command or run a program has 2 functions, one is Winexec, one is shellexecute. These two people should have seen, where Winexec is relatively simple, can run an external program directly, and shellexecute is more advanced, in addition to the external EXE, can also perform special commands.
Below we will give an example of explanation: Let’s take a look at the run of an Exe program, taking Notepad as an example:
Winexec (Pchar ('NOTEPAD .EXE'), SW_NORMAL); / / Normal mode open
Winexec (Pchar ('Notepad .exe'), SW_HIDE); // Hidden way to open
Winexec (PCHAR ('NOTEPAD.EXE'), SW_SHOWMAXIMIZED; / / Maximize mode open, software must support maximize operation, otherwise this parameter is invalid, run in normal mode
Winexec (Pchar ('NOTEPAD.EXE'), SW_SHOWMINIMIZED); / / Minimize
Shellexecute (Handle, NIL, 'NOTEPAD.EXE', NIL, NIL, SW_NORMAL); // This is opened in way with shellexecute, pay attention to the last parameter, and the same as above
Use shellexecute to pay attention to Uses shellapi, the notepad above, because it is in the system directory, so you can write the NOTEPAD.EXE file name without writing the path, if it is an exe registered in other non-environment variables, you need to bring absolute Path or relative path
Ok, the above is the easiest, let’s talk about the parameters, you know that some EXE programs can be attached to the parameters when running, here CMD as an example
For example, I want to run the ping command to perform ping 192.168.1.1
WinExec(PChar( 'cmd.exe /c ping 192.168.1.1'),SW_SHOWNORMAL);
shellexecute(handle,nil,'cmd.exe',pchar('/c ping 192.168.1.1'),nil,sw_normal);
Note that the command of the cmd needs to be run with / c to indicate the band parameters, and then keep up with the specific command so that the ping command can be executed.
The above command can indeed run successfully, but there is a shortcomings, that is, the CMD will automatically close the window after execution, if it is too fast to execute, we can’t see the result, then, what method can make CMD Don’t close the window after execution? The answer is yes, we need an extra order of order PAUSE
WinExec(PChar( 'cmd.exe /c ping 192.168.1.1 & pause'),SW_SHOWNORMAL);
We pay attention to the red part, we use a & symbol and pause, pause is the pause command in the batch, and the & symbol indicates that multiple commands can be executed. The above example shows that after executing the ping command, execute the PAUSE command, so The window will not be closed. Shellexecute also supports this method.
Below, let’s take a look at some other methods from shellexecute:
Open the web: This is too simple, everyone should know
Shellexecute (Handle, 'Open', Pchar ('http://www.baidu.com'), nil, nil, sw_shownormal; // Open Baidu.com using the default browser
Shellexecute (Handle, 'Open', 'Firefox.exe', Pchar ('http://www.baidu.com'), nil, sw_shownormal); // Open Baidu.com with Firefox Browser
Of course, Shellexecute also supports associated commands registered in the system. Such as email
ShellExecute(handle, 'open',PChar('mailto:[email protected]'),nil,nil, SW_SHOWNORMAL);
If you do this, you can open the default mail client to send an email to [email protected], if we want to bring the topics and content, it is also very good:
Shellexecute (Handle, 'Open', Pchar ('Mailto: [email protected]? Subject = This is the mail topic &[email protected]&body= mail body'), NIL, NIL, SW_SHOWNORMAL);
The topic can be automatically filled in the topic, content and copy, pay attention to the Chinese, otherwise there may be garbled.