控制台输出重定向到Memo

//函数RunCmd
void __fastcall TForm1::RunCmd(AnsiString CmdLine,TStrings *Result)
{
    HANDLE hReadPipe,hWritePipe,hParentStdout;
    SECURITY_ATTRIBUTES  sa;
    OSVERSIONINFO osVer;
    osVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osVer);
    if (osVer.dwPlatformId == VER_PLATFORM_WIN32_NT) {
        sa.nLength = sizeof(sa);
        sa.bInheritHandle = true;
        sa.lpSecurityDescriptor = NULL;
        CreatePipe(&hReadPipe,&hWritePipe,&sa, 0);
    }
    else
        CreatePipe(&hReadPipe,&hWritePipe,NULL,1024);
    Screen->Cursor = crHourGlass;
    try {
        DuplicateHandle(GetCurrentProcess(),hReadPipe,
                GetCurrentProcess(),&hParentStdout,
                0,false,DUPLICATE_SAME_ACCESS|DUPLICATE_CLOSE_SOURCE);
        SetStdHandle(STD_OUTPUT_HANDLE,hWritePipe);
        STARTUPINFO si;
        GetStartupInfo(&si);
        si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
        si.wShowWindow = SW_HIDE;
        si.cb = sizeof(STARTUPINFO);
        si.hStdOutput = hWritePipe;
        si.hStdError = hWritePipe;
        PROCESS_INFORMATION pi;
        if (CreateProcess(NULL,CmdLine.c_str(),NULL,NULL,true,0,NULL,NULL,&si,&pi)) {
            WaitForSingleObject(pi.hProcess,INFINITE);
            char sBuf[1024] = {0};
            DWORD dwTotal, dwRead;
            if (PeekNamedPipe(hReadPipe, sBuf, sizeof(sBuf)-1, &dwTotal, NULL, NULL)
                && dwTotal > 0)
            {
                do {
                    ReadFile(hParentStdout, sBuf, dwTotal, &dwRead, NULL);
                    //由于命令返回可能大于1024字节,Add方法可能造成断行,可把缓冲区设大点
                    Result->Add(AnsiString(sBuf));
                } while(dwRead >= dwTotal);
            }
            CloseHandle(pi.hProcess);
            CloseHandle(pi.hThread);
        }
    }
    __finally {
        CloseHandle(hReadPipe);
        CloseHandle(hWritePipe);
        Screen->Cursor = crDefault;
    }
}

把DOS命令返回的结果显示到Memo中,使用如下函数:
//调用方法:
RunCmd("netstat -a -n",Memo1->Lines);


阅读更多
版权声明:原创文章转载时请附上原文链接 https://blog.csdn.net/aniven/article/details/556338
个人分类: C++/BCB开发
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭