控制台程序的定向输出
void ClickedButton()
{
UpdateData();
BYTE b1, b2, b3, b4;
if (m_IpAddressCtrl.GetAddress(b1, b2, b3, b4) < 4)
return;
TCHAR cmdLine[MAX_PATH] = {0};
_stprintf(cmdLine, _T("Ping.exe %d.%d.%d.%d"), b1, b2, b3, b4);
SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, TRUE};
SECURITY_ATTRIBUTES* psa = nullptr;
DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
OSVERSIONINFO osVersion = {0};
osVersion.dwOSVersionInfoSize = sizeof(osVersion);
if (GetVersionEx(&osVersion))
{
if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
{
psa = &sa;
dwShareMode |= FILE_SHARE_DELETE;
}
}
//根据版本设置共享模式和安全属性
HANDLE hConsoleRedirect = CreateFile(_T("E:\\NetStatus.txt"), GENERIC_WRITE, dwShareMode, psa,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
ASSERT(hConsoleRedirect != INVALID_HANDLE_VALUE);
STARTUPINFO s = {sizeof(s)};
s.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//使用标准柄和显示窗口
s.hStdOutput = hConsoleRedirect;//将文件作为标准输出句柄
s.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi = {0};
if (CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, NULL, NULL, NULL, &s, &pi))
{
//创建线程,执行ping命令,测试网络是否连通
WaitForSingleObject(pi.hProcess, INFINITE);
//等待程序执行完毕
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
//关闭控制台定向输出文件句柄
CloseHandle(hConsoleRedirect);
CFile myFile(_T("E:\\NetStatus.txt"), CFile::modeRead);
ASSERT(myFile.m_hFile != NULL);
int fileLength = myFile.GetLength();
char* pBuffer = new char[fileLength + 1];
ZeroMemory(pBuffer, fileLength + 1);
myFile.Read(pBuffer, myFile.GetLength());
myFile.Close();
//删除文件
DeleteFile(_T("E:\\NetStatus.txt"));
m_editNetStatus.SetWindowText(pBuffer);//要转换为unicode
delete []pBuffer;
}