要达到DOS程序运行时不显示窗口的效果,有两种可能:
一是创建该DOS进程时,指定不创建窗口;
二是隐藏该DOS进程有窗口。
根据MSDN,CreateProcess() API的原型如下:
BOOL CreateProcess(
LPCTSTR lpApplicationName,
LPTSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCTSTR lpCurrentDirectory,
LPSTARTUPINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);
将dwCreationFlags指定为CREATE_NO_WINDOW ,即以不创建窗口方式创建DOS进程。
LPSTARTUPINFO lpStartupInfo参数又为STARTUPINFO结构,如下:
typedef struct _STARTUPINFO {
DWORD cb;
LPTSTR lpReserved;
LPTSTR lpDesktop;
LPTSTR lpTitle;
DWORD dwX;
DWORD dwY;
DWORD dwXSize;
DWORD dwYSize;
DWORD dwXCountChars;
DWORD dwYCountChars;
DWORD dwFillAttribute;
DWORD dwFlags;
WORD wShowWindow;
WORD cbReserved2;
LPBYTE lpReserved2;
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;
} STARTUPINFO,*LPSTARTUPINFO;
指定STARTUPINFO结构中WORD wShowWindow为SW_HIDE,即以不显示窗口方式创建DOS进程。
在Visusl Studio 2005中实测的结果是:创建[CMD /C] DOS进程,第一种方式可以无窗口方式创建DOS进程,而第二种方式没有正确的隐藏DOS窗口。
一个服务安装的实例:
CString sCommand = """" + sServiceExeFilePath + """" + " " + "-Install";
STARTUPINFO si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
if (CreateProcess(NULL, (char *)((LPCTSTR)sCommand), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
WaitForSingleObject(pi.hProcess, INFINITE);
bRet = TRUE;
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);