简体   繁体   English

使用 API 在另一个进程的控制台中写入(不重定向它的标准输入)

[英]Writing in another process' console using API (without redirecting it's standard input)

I'm looking for a way to write in another process' console using a WinApi, without redirecting the process' standard input.我正在寻找一种使用 WinApi 在另一个进程的控制台中写入的方法,而无需重定向进程的标准输入。

Basically, my application (written in C#) is a wrap for another console application.基本上,我的应用程序(用 C# 编写)是另一个控制台应用程序的包装。

This third-party app accepts user commands in its console.此第三方应用程序在其控制台中接受用户命令。 My wrap application must start it and write such commands in it's console.我的包装应用程序必须启动它并在它的控制台中编写这样的命令。 Yet I'm restricted to redirect the standard input stream because it causes the thisrd-party application to crash.但是我只能重定向标准输入流,因为它会导致第三方应用程序崩溃。

So I'm looking for a solution using an WinAPI, (or other way) for solving this.所以我正在寻找使用 WinAPI(或其他方式)的解决方案来解决这个问题。

Here is a brief part of the code (hoping relevant for to depict what I'm trying to do):这是代码的简短部分(希望与描述我正在尝试做的事情相关):

ProcessStartInfo startInfo = new ProcessStartInfo
{
    FileName = path
    ,Arguments = string.Join(" ", Args)
    ,UseShellExecute = false
    ,CreateNoWindow = true
    ,RedirectStandardOutput = true
    ,RedirectStandardError = true
    //,RedirectStandardInput = true //This leads the process to crash!
};

Process myProcess = new Process
{
    StartInfo = startInfo
};

myProcess.Start();

/*...*/

public void SendInput(string input)
{
    //TODO: see how to send input to process' console   
    int result = SendMessage(myProcess.Handle, 0x000C, 0, input + '\n'); // Not working :(
}

After all I found a solution by sending keystrokes to the process.毕竟我通过向进程发送按键找到了解决方案。 Eg If I want to write a full command, send the associated key code for each character form the command string, followed by an 'ENTER'.例如,如果我想编写一个完整的命令,请从命令字符串中发送每个字符的相关键代码,然后是“ENTER”。

Code:代码:

    const uint WM_KEYDOWN = 0x100;
    const uint KEY_ENTER = 13;

    [DllImport("user32.dll")]
    public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    public static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    static extern short VkKeyScanA(char ch);

    public void SendInput(string input)
    {
        IntPtr windowHandle = FindWindowByCaption(IntPtr.Zero, myProcess.MainWindowTitle);

        foreach(char c in input)
        {
            PostMessage(windowHandle, WM_KEYDOWN, ((IntPtr)VkKeyScanA(c)), IntPtr.Zero);
        }
        PostMessage(windowHandle, WM_KEYDOWN, ((IntPtr)KEY_ENTER), IntPtr.Zero);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM