在命令行中启动一个应用程序后,由于应用程序需要处理鼠标消息,我只能做成窗口应用程序,但要如何才能把运行结果输出到那个命令行。
------解决思路----------------------
窗体函数没有继承命令行窗口所以没办法写
可以把代码分割到一个命令行程序和一个窗体程序,然后窗体程序里通知命令行程序写输出。
------解决思路----------------------
仅供参考:
#pragma comment(lib,"user32")
#include <stdio.h>
#include <windows.h>
int main() {
SECURITY_ATTRIBUTES sa = {0};
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
HANDLE hPipeOutputRead = NULL;
HANDLE hPipeOutputWrite = NULL;
HANDLE hPipeInputRead = NULL;
HANDLE hPipeInputWrite = NULL;
BOOL bTest = 0;
DWORD dwNumberOfBytesRead = 0;
DWORD dwNumberOfBytesWrite = 0;
CHAR szMsg[100];
CHAR szBuffer[256];
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
// Create pipe for standard output redirection.
CreatePipe(&hPipeOutputRead, // read handle
&hPipeOutputWrite, // write handle
&sa, // security attributes
0 // number of bytes reserved for pipe - 0 default
);
// Create pipe for standard input redirection.
CreatePipe(&hPipeInputRead, // read handle
&hPipeInputWrite, // write handle
&sa, // security attributes
0 // number of bytes reserved for pipe - 0 default
);
// Make child process use hPipeOutputWrite as standard out,
// and make sure it does not show on screen.
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW
------解决思路----------------------
STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdInput = hPipeInputRead;
si.hStdOutput = hPipeOutputWrite;
si.hStdError = hPipeOutputWrite;
CreateProcess (
NULL, "cmd.exe",
NULL, NULL,
TRUE, 0,
NULL, NULL,
&si, &pi);
// Now that handles have been inherited, close it to be safe.
// You don't want to read or write to them accidentally.
CloseHandle(hPipeOutputWrite);
CloseHandle(hPipeInputRead);
// Now test to capture DOS application output by reading
// hPipeOutputRead. Could also write to DOS application
// standard input by writing to hPipeInputWrite.
sprintf(szMsg, "dir *.txt /b\nexit\n");
WriteFile(
hPipeInputWrite, // handle of the write end of our pipe
&szMsg, // address of buffer that send data
18, // number of bytes to write
&dwNumberOfBytesWrite,// address of number of bytes read
NULL // non-overlapped.
);
while(TRUE)
{
bTest=ReadFile(
hPipeOutputRead, // handle of the read end of our pipe
&szBuffer, // address of buffer that receives data
256, // number of bytes to read
&dwNumberOfBytesRead, // address of number of bytes read
NULL // non-overlapped.
);
if (!bTest){
sprintf(szMsg, "Error #%d reading pipe.",GetLastError());
MessageBox(NULL, szMsg, "WinPipe", MB_OK);
break;
}
// do something with data.
szBuffer[dwNumberOfBytesRead] = 0; // null terminate
MessageBox(NULL, szBuffer, "WinPipe", MB_OK);
}
// Wait for CONSPAWN to finish.
WaitForSingleObject (pi.hProcess, INFINITE);
// Close all remaining handles
CloseHandle (pi.hProcess);
CloseHandle (hPipeOutputRead);
CloseHandle (hPipeInputWrite);
return 0;
}
再供参考:
console屏幕处理例子程序。终端窗口屏幕处理相关API使用例子。来自MSVC20\SAMPLES\win32\console\ http://download.csdn.net/detail/zhao4zhong1/3461309