问题:
关于Windows下通过调用system函数,可执行一段dos命令。
但是,每次我们执行dos命令,总会弹出一个黑色的弹窗,虽然是转瞬即逝,但是依旧不是很完美。
比如以下程序:
#include <iostream>
using namespace std;
int main()
{
/*
主函数中调用bat程序之前写入一些dos命令!
*/
CFile file;
if(file.Open("C:\Users\Cain\Desktop\test.bat",CFile::modeCreate | CFile::modeWrite)
{
CString str1,str2;
str1.Format("set path=%path%;C:\Users\Cain\bin");
str.Format("echo %path%");
//其实下面不用这样写,\n可以写到str1、str2中,但是为了你们看着清晰,so!
file.Write(str1,str1.GetLength());
file.Write("\n",1);
file.Write(str2,str2.GetLength());
file.Write("\n",1);
file.Close();
}
::system("C:\Users\Cain\Desktop\test.bat"); //调用bat批处理程序
}
解决方法:
网上有很多中解决办法,system函数好象没有提供这样的功能
你可以使用CreateProcess来启动一个进程。
关于CreateProcess如下:
BOOL CreateProcess(
LPCTSTR lpApplicationName, // name of executable module
LPTSTR lpCommandLine, // command line string
LPSECURITY_ATTRIBUTES lpProcessAttributes, // SD
LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD
BOOL bInheritHandles, // handle inheritance option
DWORD dwCreationFlags, // creation flags
LPVOID lpEnvironment, // new environment block
LPCTSTR lpCurrentDirectory, // current directory name
LPSTARTUPINFO lpStartupInfo, // startup information
LPPROCESS_INFORMATION lpProcessInformation // process information
);
但是这里我是不推荐使用上面方法的,可以掌握,但是不推荐。
为了实现一个这样的小功能,去写这么久的程序,还开进程,实在是有些不值得。
下面我推荐的这种方法,我们改一下程序。请看:
#include <iostream>
using namespace std;
int main()
{
/*
主函数中调用bat程序之前写入一些dos命令!
*/
CFile file;
if(file.Open("C:\Users\Cain\Desktop\test.bat",CFile::modeCreate | CFile::modeWrite)
{
CString str1,str2;
str1.Format("set path=%path%;C:\Users\Cain\bin");
str.Format("echo %path%");
//其实下面不用这样写,\n可以写到str1、str2中,但是为了你们看着清晰,so!
file.Write(str1,str1.GetLength());
file.Write("\n",1);
file.Write(str2,str2.GetLength());
file.Write("\n",1);
file.Close();
}
#ifndef 1
::system("C:\Users\Cain\Desktop\test.bat"); //调用bat批处理程序
#else //下面代码可以省去小黑窗
WinExec("C:\Users\Cain\Desktop\test.bat",SW_HIDE);
#endif
}
对比之下,大家应该知道什么容易吧,不要总是自己为难自己,能简单点就简单点。
关于此问题,就大概说这些吧!谢谢。