Con*_*ngo 2 .net c# visual-studio
有没有办法将[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();
}
}
Run Code Online (Sandbox Code Playgroud)
这个答案也适用回避的事实,呼吁.Abort对ReadLine()将在C#中行不通,因为ReadLine()在非托管代码中的Windows内核运行深.
这个答案优于任何仅在当前进程具有焦点时才有效的答案,例如SendKeys和Input Simulator.