如何写入控制台输入并获取控制台句柄?

时间:2009-05-12 20:17:29

标签: c# console

我希望用户能够在输入流中拥有一些他们可以更改的数据。我查看了下面的函数,但我不确定如何从Console类获取Console句柄。

    [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool WriteConsoleInput(
        IntPtr hConsoleInput,
        [Out] INPUT_RECORD[] lpBuffer,
        int nLength,
        out int lpNumberOfEventsWritten);


    public static void WriteConsoleInput()
    {
        UInt32 STD_INPUT_HANDLE = 0xfffffff6;
        IntPtr hConsoleInput = GetStdHandle(STD_INPUT_HANDLE);


        INPUT_RECORD[] lpBuffer = new INPUT_RECORD[2];

        // I tried using uChar (short) as well. 
        lpBuffer[0].Event.KeyEvent.wVirtualKeyCode = 0x41; // A
        lpBuffer[1].Event.KeyEvent.wVirtualKeyCode = 0x5A; // Z

        int nLength = lpBuffer.Length;
        int lpNumberOfEventsWritten;
        if (!WriteConsoleInput(
            hConsoleInput,
            lpBuffer,
            nLength,
            out lpNumberOfEventsWritten))
        {
            // Don't get here.
            Console.WriteLine("Error: {0}", GetLastError());
        }
    } // A breakpoint here shows that lpNumberOfEventsWritten is 2

    ...
    ...
    ...

    Console.Write("Input something: ");
    WriteConsoleInput();
    String input = Console.ReadLine();
    Console.WriteLine("input = {0}", input);

我在“输入内容:”后面的屏幕上看不到任何内容。如果我只是按Enter键,则输入为空字符串。

2 个答案:

答案 0 :(得分:1)

这有用吗?

public class ConsoleHandles
{
  private const uint STD_INPUT_HANDLE = 0xfffffff6;
  private const uint STD_OUTPUT_HANDLE = 0xfffffff5;
  private const uint STD_ERROR_HANDLE = 0xfffffff4;

  [DllImport("kernel32.dll")]
  private static extern int GetStdHandle(uint nStdHandle);

  public Int32 Stdin { get { return GetStdHandle(STD_INPUT_HANDLE ); } }
  //etc
}

答案 1 :(得分:0)

我建议只使用P / Invoke,而不是将托管和非托管混合(这可能会使假设System.Console混乱)。

MSDN有一个例子:http://msdn.microsoft.com/library/ms685035