views:

875

answers:

4

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.

What should I do?

+2  A: 

Have you seen this great tool - AutoIt. This is a scripting tool. To send a backspace you would use Send("{BACKSPACE}")

This is a great tool and it can help in automating many manual clicks/double-clicks/etc.

Is this relevant to your question ?

Subbu
Hi, it is relevant, but I prefer a solution that I could use directly in .NET.
Jader Dias
@Jader; there is a dll available for AutoIt that you can easily add to your application...
jvenema
A: 

If you have a Windows Forms window that you can send the keys to, then SendKeys might be an appropriate solution.

For pressing backspace and Ctrl+C, that should be

SendKeys.Send("{BACKSPACE}^C");
AndiDog
Sending Ctrl+C like that does not actually work in a process, it should be ^{BREAK}...
tommieb75
+7  A: 

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:

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.

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.

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);
Remus Rusanu
http://www.google.com/codesearch/p?hl=en#ncfzeHH4QLA/pubs/consoledotnet/consoledotnet.zip%7CYrqh4ujA6zA/ConsoleDotNet/WinCon.cs
Jader Dias
+2  A: 
tommieb75