Is there a way to poke the [enter] keystroke into the current process, to force the thread blocking on Console.ReadLine() to exit?
More Info (you can ignore this)
I have a C# console app which is running another thread which is blocking on Console.ReadLine(). As Console.ReadLine calls a native windows thread that runs deep in the bowels of unmanaged code within Windows, it won't abort until it unblocks, and that won't happen until it receives a keypress on the keyboard.
Thus, when I call ".Abort" on this thread, within C# .NET, it won't about until I manually press [enter] on the console. I want to automate this keypress.
http://inputsimulator.codeplex.com/ works just brilliantly in a console app, as long as the current console app has the focus.
Demo code:
This code does not work unless the current console app does not have focus, which leads to all sorts of problems with keys getting poked into other 3rd party applications if said console process is designed to run in the background.
See also answer to Interrupt Console.ReadLine, and new accepted answer that involves using PostMessage.
Well, you could always use System.Windows.Forms.SendKeys.SendWait(string keyStrokes) to inject the Enter keystroke - this would obviously require a reference to System.Windows.Forms.
However, I would be inclined to question my arcitecture and perhaps use a proper thread waiting mechanism. There are several ways to achieve this - here's an article that I have used before to help in this area : http://www.albahari.com/threading/part2.aspx
Cheers, Chris.
Use PostMessage to send [enter] into the current process:
This answer also works around the fact that calling
.Abort
onReadLine()
won't work in C#, asReadLine()
is running in unmanaged code deep within the Windows kernel.This answer is superior to any answers that only work if the current process has the focus, such as SendKeys and Input Simulator.