system调用命令行命令而不显示命令行窗口

system调用命令行命令而不显示命令行窗口

通常用system调用命令行命令时都会弹出黑底白字的命令行窗口,下面的代码可以不显示弹出的命令行窗口。

代码如下

 
 1 #pragma comment( linker, "/subsystem:/"windows/" /entry:/"mainCRTStartup/"" ) // 设置入口地址

 2 #include   <windows.h>   

 3 #include   <stdio.h>   

 4 

 5 #define   COMMENDLINE   "ping 127.0.0.1"

 6 

 7 //调用命令行命令而不显示命令行窗口

 8 BOOL system_hide(char* CommandLine)   

 9 {   

10     SECURITY_ATTRIBUTES   sa;   

11     HANDLE   hRead,hWrite;   

12 

13     sa.nLength   =   sizeof(SECURITY_ATTRIBUTES);   

14     sa.lpSecurityDescriptor   =   NULL;   

15     sa.bInheritHandle   =   TRUE;   

16     if   (!CreatePipe(&hRead,&hWrite,&sa,0))     

17     {   

18         return   FALSE;   

19     }     

20 

21     STARTUPINFO   si;   

22     PROCESS_INFORMATION   pi;     

23     si.cb   =   sizeof(STARTUPINFO);   

24     GetStartupInfo(&si);     

25     si.hStdError   =   hWrite;   

26     si.hStdOutput   =   hWrite;   

27     si.wShowWindow   =   SW_HIDE;   

28     si.dwFlags   =   STARTF_USESHOWWINDOW   |   STARTF_USESTDHANDLES;   

29     //关键步骤,CreateProcess函数参数意义请查阅MSDN   

30     if   (!CreateProcess(NULL, CommandLine, NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))     

31     {   

32         return   FALSE;   

33     }   

34     CloseHandle(hWrite);   

35 

36     char   buffer[4096]   =   {0};   

37     DWORD   bytesRead;     

38     while(true)     

39     {   

40         memset(buffer,0,strlen(buffer));

41         if(ReadFile(hRead,buffer,4095,&bytesRead,NULL)==NULL)   

42             break;   

43         //buffer中就是执行的结果,可以保存到文本,也可以直接输出   

44         //printf(buffer);//这行注释掉就可以了   

45         Sleep(100);     

46     }     

47     return   TRUE;   

48 }   

49 

50 int main(int argc, char* argv[])   

51 {   

52     system_hide(COMMENDLINE);//不显示命令窗口

53     //system(COMMENDLINE);//显示命令行窗口

54     return 0;   

55 }

http://blog.csdn.net/cxaa21/article/details/5031404#

你可能感兴趣的:(System)