.NET调用将击键发送到当前进程,这是一个控制台应用程序?

有没有办法将[enter]键击到当前进程中,强制在Console.ReadLine()上阻塞线程?

更多信息(你可以忽略这个)

我有一个C#控制台应用程序正在运行另一个在Console.ReadLine()上阻塞的线程。 由于Console.ReadLine调用在Windows中非托管代码的内部深处运行的本机Windows线程,因此在解除阻塞之前它不会中止,并且直到它在键盘上接收到按键才会发生。

因此,当我在这个线程上调用“.Abort”时,在C#.NET中,直到我在控制台上手动按[enter]才会这样做。 我想自动化这个按键。

使用PostMessage将[enter]发送到当前进程:

class Program { [DllImport("User32.Dll", EntryPoint = "PostMessageA")] private static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam); const int VK_RETURN = 0x0D; const int WM_KEYDOWN = 0x100; static void Main(string[] args) { Console.Write("Switch focus to another window now to verify this works in a background process.\n"); ThreadPool.QueueUserWorkItem((o) => { Thread.Sleep(4000); var hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; PostMessage(hWnd, WM_KEYDOWN, VK_RETURN, 0); }); Console.ReadLine(); Console.Write("ReadLine() successfully aborted by background thread.\n"); Console.Write("[any key to exit]"); Console.ReadKey(); } } 

这个答案也解决了以下事实:在ReadLine()上调用.Abort将不能在C#中工作,因为ReadLine()在Windows内核深处的非托管代码中运行。

这个答案优于任何仅在当前进程具有焦点时才有效的答案,例如SendKeys和Input Simulator 。

只要当前的控制台应用程序具有焦点, http://inputsimulator.codeplex.com/就可以在控制台应用程序中运行得非常出色。

演示代码:

 InputSimulator.SimulateKeyPress(VirtualKeyCode.RETURN); Console.Write("[enter] is now queued in the buffer for this console app.\n"); Console.ReadLine(); Console.Write("Program go to here, without the user pressing [enter] on the keyboard.\n"); Console.Write("[any key to exit]\n"); Console.ReadKey(); 

除非当前控制台应用程序没有焦点,否则此代码不起作用,如果所述控制台进程设计为在后台运行,则会导致键被引入其他第三方应用程序的各种问题。

另请参阅Interrupt Console.ReadLine的答案,以及涉及使用PostMessage的新接受的答案。

好吧,你总是可以使用System.Windows.Forms.SendKeys.SendWait(string keyStrokes)来注入Enter键 – 这显然需要引用System.Windows.Forms。

但是,我倾向于质疑我的arcitecture并且可能使用适当的线程等待机制。 有几种方法可以实现这一目标 – 这是我以前用过的一篇文章来帮助这个领域: http : //www.albahari.com/threading/part2.aspx

干杯,克里斯。