Dos Console test...........(1)

来源:互联网 发布:mac照片如何导入iphone 编辑:程序博客网 时间:2024/05/22 13:07
// Test.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <conio.h>#include <stdio.h>#include <PROCESS.H>#include <windows.h>#include <fstream>#include <SHELLAPI.H>using namespace std;#define   EXECDOSCMD   "ipconfig"   //可以换成你的命令 VOID Thread_print (PVOID pvoid){while(1){printf("Hello world\n\n");Sleep(1000);}}bool executePackage(LPCWSTR fileName, LPCWSTR args, LPCWSTR baseDir, bool wait)  {      SHELLEXECUTEINFOW sei = { sizeof(SHELLEXECUTEINFOW) };      sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;      sei.lpFile = fileName;      sei.lpParameters = args;      sei.lpDirectory = baseDir;      if (!ShellExecuteExW(&sei)) {          return false;      }      if (wait) {          HANDLE hProcess = sei.hProcess;          if (hProcess != 0) {              WaitForSingleObject(hProcess, INFINITE);              CloseHandle(hProcess);          }      }      return true;  }  void EXEC (){ SECURITY_ATTRIBUTES   sa; HANDLE   hRead,hWrite; sa.nLength   =   sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor   =   NULL; sa.bInheritHandle   =   TRUE; if   (!CreatePipe(&hRead,&hWrite,&sa,0))   { return; }   STARTUPINFO   si; PROCESS_INFORMATION   pi;   si.cb   =   sizeof(STARTUPINFO); GetStartupInfo(&si);   si.hStdError   =   hWrite; si.hStdOutput  =   hWrite;si.hStdInput   =   hRead;si.wShowWindow =   SW_HIDE; si.dwFlags   =   STARTF_USESHOWWINDOW   |   STARTF_USESTDHANDLES; //关键步骤,CreateProcess函数参数意义请查阅MSDN if   (!CreateProcess(NULL,   EXECDOSCMD ,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))   { return; } CloseHandle(hWrite); char   buffer[4096]   =   {0}; DWORD   bytesRead;   ofstream outfile("log.txt");_beginthread(Thread_print, 0, NULL);while   (true)   { if   (ReadFile(hRead,buffer,4095,&bytesRead,NULL)   ==   NULL) {break; }printf("printing.....\n");//buffer中就是执行的结果,可以保存到文本,也可以直接输出 //printf(buffer); outfile << buffer;Sleep(200);   }outfile.close();return;}int main(){ //EXEC();if(executePackage(LPCWSTR("mspaint"),LPCWSTR(""),LPCWSTR("C:\\Windows"),false)){printf("exec successfully...\n");}else{printf("exec failed...\n");}//system("ping www.baidu.com");//system("ping 127.0.0.1");// system("ipconfig");getch();return 0;}

原创粉丝点击