例如,假设我有一个控制台应用程序,如果我尝试从 Windows 资源管理器启动此控制台应用程序,它将不起作用,它只会关闭,但我可以从我的 GUI 应用程序或 Windows 命令控制台 (cmd. exe)并传递一些开关(参数?)给它。
它会工作。但是,一旦您的程序退出,控制台窗口就会消失。如果您想让用户有机会在窗口关闭之前读取控制台应用程序的输出,只需使用单个结束程序即可
Readln;
或
Writeln('Press Enter to exit.');
Readln;
如果您想在 GUI 应用程序中使用控制台窗口进行输出(或输入),可以试试 AllocConsole 和 FreeConsole 函数。
命令行参数(例如myapp.exe /OPEN "C:\some dir\file.txt" /THENEXIT)可用于所有类型的 Windows 应用程序,包括 GUI 应用程序和控制台应用程序。只需使用ParamCount 和ParamStr 函数即可。
如何创建接受命令行参数的控制台应用程序
在 Delphi IDE 中,选择 File/New/Console Application。然后写
program Project1;
{$APPTYPE CONSOLE}
uses
Windows, SysUtils;
var
freq: integer;
begin
if ParamCount = 0 then
Writeln('No arguments passed.')
else if ParamCount >= 1 then
if SameText(ParamStr(1), '/msg') then
begin
if ParamCount = 1 then
Writeln('No message to display!')
else
MessageBox(0, PChar(ParamStr(2)), 'My Console Application',
MB_ICONINFORMATION);
end
else if SameText(ParamStr(1), '/beep') then
begin
freq := 400;
if ParamCount >= 2 then
if not TryStrToInt(ParamStr(2), freq) then
Writeln('Invalid frequency: ', ParamStr(2));
Windows.Beep(freq, 2000);
end;
end.
编译程序。然后打开一个命令处理器(CMD.EXE),进入Project1.exe所在的目录。
那就试试
C:\Users\Andreas Rejbrand\Documents\RAD Studio\Projects>project1
No arguments passed.
C:\Users\Andreas Rejbrand\Documents\RAD Studio\Projects>project1 /msg
No message to display!
C:\Users\Andreas Rejbrand\Documents\RAD Studio\Projects>project1 /msg "This is a test."
C:\Users\Andreas Rejbrand\Documents\RAD Studio\Projects>project1 /beep
C:\Users\Andreas Rejbrand\Documents\RAD Studio\Projects>project1 /beep 600
C:\Users\Andreas Rejbrand\Documents\RAD Studio\Projects>
如何传递三个参数
if ParamCount >= 1 then
begin
if SameText(ParamStr(1), '/CONVERT') then
begin
// The user wants to convert
if ParamCount <= 2 then
begin
Writeln('Too few arguments!');
Exit;
end;
FileName1 := ParamStr(2);
FileName2 := ParamStr(3);
DoConvert(FileName1, FileName2);
end;
end;