How to send keys data to a Console window without having focus

后端 未结 1 556
抹茶落季
抹茶落季 2021-01-28 10:19

I\'ve been trying to send data to a console window without it having focus. I\'ve used a simple Keyboard Hook from here: Capture keystroke without focus in console

I\'ve

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-28 10:52

    You can replace the standard input stream with your own and then write to it. To do that call Console.SetIn with your new stream.

    Here is a very little example:

        static void Main(string[] args)
        {
    
            MemoryStream ms = new MemoryStream();
            StreamReader sr = new StreamReader(ms);
            StreamWriter sw = new StreamWriter(ms);
            Console.SetIn(sr);
    
    
            sw.WriteLine("Hi all!");
            ms.Seek(0, SeekOrigin.Begin);
            string line = Console.ReadLine();
    
            Console.WriteLine(line);
    
        }
    

    Only problem here is you must control the stream's position and if the Console reaches the end of the stream it will continue returning a null value.

    There are many solutions for those problems, from handling the null values at the console app level to creating a custom StreamReader which locks until a line has been written (Console uses by default a stream of type SyncTextReader, but it's private).

    0 讨论(0)
提交回复
热议问题