C++Builder中调用外部程序
软件世界
有时,在程序中需要调用其他外部程序,比如在需要记录文本时可能需要打开记事本,在需要计算时可能需要打开计算器等。
在BCB(Borland C++ Builder)中有多种方法可以实现这一点。
1.用WinExec()实现
例如调用外部程序“记事本”:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
WinExec("c:\\windows\\notepad.exe",1);
}
2.用ShellExecute()或者ShellExecuteEx()实现
//file-文件名称
//para-外部程序调用参数,没有即为0
//使用ShellExecuteEx()可以更好地控制程序的调用
int RunProgram(char *file,char *para)
{
SHELLEXECUTEINFO execinfo;
memset(&exeinfo,0,sizeof(execinfo));
execinfo.cbSize = sizeof(execinfo);
execinfo.lpVerb = "open";
execinfo.lpFile = file;
execinfo.plParameters = para;
execinfo.fMask = SEE_MASK_NOCLOSEPROCESS;
execinfo.nShow = SW_SHOWDEFAULT;
if (!ShellExecuteEx(&execinfo))
{
char data[100];
sprintf(data,"打开程序%s'错误",file);
MessageBox(0,data,"错误",MB_OK);
return -1;
}
return 0;
}
通过以上函数即可直接调用外部程序,比如调用“记事本”,输入以下代码即可:RunProgram("c:\\windows\\notepad.exe",NULL);
如果直接使用ShellExecute()函数将简单很多,比如调用外部程序“记事本”,用以下语句来完成:
ShellExecute(0,"Open","c:\\windows\\notepad.exe",0,0,SW_SHOW);
提示:ShellExecute()和ShellExecuteEx()的区别在于后者在对外部程序调用时可使用更多的功能。