的System.Diagnostics.Process公开名为StandardInput的StreamWriter,它仅接受字符据我所知。
System.Diagnostics.Process exposes a StreamWriter named StandardInput, which accepts only characters as far as I know.
但我需要发送击键,以及和一些按键不能很好地映射到人物。
But I need to send keystrokes as well, and some keystrokes don't map well to characters.
我应该怎么办?
您在混合与控制信号输入流。控制台程序有一个默认的输入流,你可以用StandardInput控制,因为你已经知道了。但是,按Ctrl-C和Ctrl-中断无法通过此流发送到进程的人物,而是他们是不是控制信号的过程中接收使用已注册的信号处理程序,看到的 CTRL + C和CTRL + BREAK信号的:
You are mixing input streams with control signals. A console process has a default input stream which you can control with the StandardInput, as you already know. But Ctrl-C and Ctrl-Break are not characters sent to the process through this stream, but instead they are instead control signals that the process receives using the registered signal handlers, see CTRL+C and CTRL+BREAK Signals:
在默认情况下,当一个控制台窗口有 键盘焦点,CTRL + C或 CTRL + BREAK被视为一个信号 (SIGINT或SIGBREAK),而不是 键盘输入。
By default, when a console window has the keyboard focus, CTRL+C or CTRL+BREAK is treated as a signal (SIGINT or SIGBREAK) and not as keyboard input.
要发送假信号到过程中,你可以使用GenerateConsoleCtrlEvent和发送任何 CTRL_C_EVENT
或 CTRL_BREAK_EVENT
。这个API没有净等同,所以你要的PInvoke它。
To send fake signals to a process you can use GenerateConsoleCtrlEvent
and send either CTRL_C_EVENT
or CTRL_BREAK_EVENT
. This API has no .Net equivalent, so you have to PInvoke it.
要由使用它。NET你只需要包括函数定义:
To use it from .NET you simply need to include the function definition:
const int CTRL_C_EVENT = 0;
const int CTRL_BREAK_EVENT = 1;
[DllImport("kernel32.dll")]
static extern bool GenerateConsoleCtrlEvent(
uint dwCtrlEvent,
uint dwProcessGroupId);