[英]How to read console output of a process without redirecting standard output?
[英]Writing in another process' console using API (without redirecting it's standard input)
我正在寻找一种使用 WinApi 在另一个进程的控制台中写入的方法,而无需重定向进程的标准输入。
基本上,我的应用程序(用 C# 编写)是另一个控制台应用程序的包装。
此第三方应用程序在其控制台中接受用户命令。 我的包装应用程序必须启动它并在它的控制台中编写这样的命令。 但是我只能重定向标准输入流,因为它会导致第三方应用程序崩溃。
所以我正在寻找使用 WinAPI(或其他方式)的解决方案来解决这个问题。
这是代码的简短部分(希望与描述我正在尝试做的事情相关):
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 :(
}
毕竟我通过向进程发送按键找到了解决方案。 例如,如果我想编写一个完整的命令,请从命令字符串中发送每个字符的相关键代码,然后是“ENTER”。
代码:
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.