天天看点

将CMD的输入输出重定向到自己的进程

void CreateMyPipe()

{

    //创建管道

    CreatePipe(&hReadPipe, &hWritePipe, NULL, NULL);

    CreatePipe(&hChildReadPipe, &hChildWritePipe, NULL, NULL);

    SetHandleInformation(hWritePipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);

    SetHandleInformation(hChildReadPipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);

    DWORD dwWord = PIPE_NOWAIT;

    SetNamedPipeHandleState(hReadPipe, &dwWord, NULL, NULL);

    //创建CMD进程

    PROCESS_INFORMATION stProcessInfo;

    STARTUPINFO stStartInfo;

    ::ZeroMemory(&stStartInfo,sizeof(stStartInfo));

    stStartInfo.cb = sizeof(stStartInfo);

    stStartInfo.dwFlags = STARTF_USESTDHANDLES;//STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;

    stStartInfo.hStdError = hWritePipe;

    stStartInfo.hStdOutput = hWritePipe;

    stStartInfo.hStdInput = hChildReadPipe;

    if(!CreateProcessA(NULL, "cmd.exe/0", NULL, NULL, true, DETACHED_PROCESS, NULL, NULL, &stStartInfo, &stProcessInfo))

    {

        MessageBox("启动进程失败!");

        return;

    }else{

        CloseHandle(stProcessInfo.hThread);

        CloseHandle(stProcessInfo.hProcess);

    }

    //从管道中读出数据, 该数据通常为CMD的版本及版权信息

    ReadFromChildPipe();

}

void ReadFromChildPipe()

    //读取管道中所有可读取的数据并写入到txtMessage中

    DWORD nRead;

    char* strBuffer = new char[65536];

    long nBufferLen;

    nRead = -1;

    while(nRead != 0)

        nBufferLen = 65536;

        memset(strBuffer, 0, 65536);

        Sleep(30);

        ReadFile(hReadPipe, strBuffer, nBufferLen, &nRead, NULL);

        if(nRead != 0)

        {

            GetDlgItem(IDC_EDIT_MSG)->SetWindowTextA(strBuffer);

        }

    delete[] strBuffer;

void WriteMyPipe()

    //将命令写入管道

    DWORD nWrite;

    char* strBuffer = new char[300];

    memset(strBuffer, 0, 300);

    memcpy(strBuffer, "dir/r/n", 5);

    if (WriteFile(hChildWritePipe, strBuffer, 5, &nWrite, NULL))

        ReadFromChildPipe();

        MessageBox("写入失败");

HANDLE hReadPipe;

HANDLE hWritePipe;

HANDLE hChildReadPipe;

HANDLE hChildWritePipe;

CloseHandle(hReadPipe);

CloseHandle(hWritePipe);

CloseHandle(hChildReadPipe);

CloseHandle(hChildWritePipe);