vc 执行命令行输出到richedit空间

控件初始化

BOOL CMFCApplication1App::InitInstance()

AfxInitRichEdit2();

 

void ThreadProc(void* p)
{
    CMFCApplication1Dlg* dlg = (CMFCApplication1Dlg*)p;
    dlg->ExecCmd();
}

void CMFCApplication1Dlg::OnBnClickedButton1()
{

    CString str;
    //ExecCmd();
    std::thread t(ThreadProc, this);
    t.detach();

}






void CMFCApplication1Dlg::AppendText(CString str)
{
    m_ctrlRichEdit.PostMessage(WM_VSCROLL, SB_BOTTOM, 0);
    m_ctrlRichEdit.SetSel(-1, -1);
    m_ctrlRichEdit.ReplaceSel((LPCTSTR)str);
}


int CMFCApplication1Dlg::ExecCmd()
{
    SECURITY_ATTRIBUTES sa;
    HANDLE hRead, hWrite;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;
    if (!CreatePipe(&hRead, &hWrite, &sa, 0))
    {
        DWORD dErr = GetLastError();
        CString szInfo;
        szInfo.Format(_T("Fail to Create Pipe Error: %d"), dErr);
        MessageBox(szInfo);
        return -1;
    }
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    si.cb = sizeof(STARTUPINFO);
    GetStartupInfo(&si);
    si.hStdError = hWrite;
    si.hStdOutput = hWrite;
    si.wShowWindow = SW_HIDE;
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    TCHAR szCommand[] = _T("cmd.exe /k ipconfig/all");
    if (!CreateProcess(NULL, szCommand, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
    {
        MessageBox(_T("Fail to create process"));
        return -2;
    }
    CloseHandle(hWrite);
    char buffer[128] = { 0 };
    DWORD bytesRead;

    for (;;)
    {
        if (ReadFile(hRead, buffer, 128, &bytesRead, NULL) == NULL || bytesRead == 0)
        {
            break;//读取结束
        }
        else
        {
            TCHAR szShow[128] = { 0 };
            MultiByteToWideChar(CP_ACP, NULL, buffer, 128, szShow, 128);
            AppendText(szShow);
        }
    }


    return 0;
    // __super::OnOK();  
}

 

posted on 2021-03-11 15:14  alantop  阅读(127)  评论(0编辑  收藏  举报