【Shell编程】问题:取消system函数调用dos出现的黑窗口

问题:

关于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	
}

对比之下,大家应该知道什么容易吧,不要总是自己为难自己,能简单点就简单点。
关于此问题,就大概说这些吧!谢谢。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cain Xcy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值