将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();
    }else{
        MessageBox("写入失败");
    }


    delete[] strBuffer;
}


HANDLE hReadPipe;
HANDLE hWritePipe;
HANDLE hChildReadPipe;
HANDLE hChildWritePipe;


CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
CloseHandle(hChildReadPipe);
CloseHandle(hChildWritePipe);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值