前几天在写console程序的时候忽然想起来“如何判断当前程序是直接运行还是从CMD窗口中运行”的问题,网上搜索了一下,并无明确结果,为此我请教了一下天杀,他给我出了2个办法。第一个办法是通过GetStartupInfo得到当前窗口的 Title,从下图可以看到直接运行的时候是只有文件名,如果从cmd下面运行会有完整的路径和文件名
例程:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils,
windows;
var
Info:STARTUPINFO;
begin
GetStartupInfo(Info);
writeln(Info.lpTitle);
readln;
end.
上面 STARTUPINFO结构体的 dwFlags 位也能反映这个差别:
STARTF_TITLEISLINKNAME 0x00000800
The lpTitle member contains the path of the shortcut file (.lnk) that the user invoked to start this process. This is typically set by the shell when a .lnk file pointing to the launched application is invoked. Most applications will not need to set this value.
This flag cannot be used with STARTF_TITLEISAPPID.
完整程序下载 cmd1