📄 faq8.htm
字号:
<HTML>
<HEAD>
<TITLE>Fetch the command line arguments to the application</TITLE>
<META NAME="Author" CONTENT="Harold Howe">
</HEAD>
<BODY BGCOLOR="WHITE">
<CENTER>
<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH="640">
<TR>
<TD>
<H3>
Fetch the command line arguments to the application
</H3>
<P>
You can use two different techniques to solve this problem.
</P>
<P>
<B>Method 1:</B> The first, and probably the easiest, method is to call the
VCL <TT>ParamStr()</TT> function. You can use the <TT>ParamCount()</TT>
function to determine how many command line arguments were passed to the
program.
</P>
<P> <TT>ParamStr</TT> takes an integer argument and returns an
<TT>AnsiString</TT> object. <TT>ParamStr</TT> will return the full path
of the executable if you pass a value of 0. Passing 1 returns the first
command line argument after the program name. Passing 2 returns the second
argument, and on and on.
</P>
<P>
To practice, start a new project and place 5 labels onto the main form.
Add this code to the form's constructor:
</P>
<pre>
Label1<b>-></b>Caption <b>=</b> ParamStr<b>(</b><font color="blue">0</font><b>)</b><b>;</b>
Label2<b>-></b>Caption <b>=</b> ParamStr<b>(</b><font color="blue">1</font><b>)</b><b>;</b>
Label3<b>-></b>Caption <b>=</b> ParamStr<b>(</b><font color="blue">2</font><b>)</b><b>;</b>
Label4<b>-></b>Caption <b>=</b> ParamStr<b>(</b><font color="blue">3</font><b>)</b><b>;</b>
Label5<b>-></b>Caption <b>=</b> ParamStr<b>(</b><font color="blue">4</font><b>)</b><b>;</b>
</pre>
<P>
Run the program. On my system I see:
<PRE>
E:\CBUILDER\PROJECTS\PROJECT1.EXE
</PRE>
<P>
Labels 2 through 5 are blank because I didn't pass any arguments to the
program. Close the program and select Run | Parameters from the C++Builder
menu. Type in a few arguments(<TT>-debug -testing -param</TT>) and run the
program again. You should see:
</P>
<PRE>
E:\CBUILDER\PROJECTS\PROJECT1.EXE
-debug
-testing
-param
</PRE>
<P>
<B>Note:</B> <TT>ParamStr</TT> is smart about directories with spaces in their
names. To prove this, copy the EXE to the Program Files directory and
run it from there. Observe that <TT>ParamStr(0)</TT> contains the entire path,
including the space.
</P>
<P>
<B>Method 2:</B> The second method is to call the API <TT>GetCommandLine</TT>
function. <TT>GetCommandLine</TT> takes no arguments and returns a C style
char * containing the entire command line. You will have to parse the
string to extract the commands.
</P>
<pre>
Label5<b>-></b>Caption <b>=</b> AnsiString<b>(</b>GetCommandLine<b>(</b><b>)</b><b>)</b><b>;</b>
</pre>
<P>
On my system, Label5 contains (note the added quotes):
</P>
<PRE>
"E:\CBuilder\Projects\Project1.exe" -debug -testing -param
</PRE>
</TD> </TR>
</TABLE>
</CENTER>
</BODY>
</HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -