How to interrupt Console.ReadLine

后端 未结 10 815
情歌与酒
情歌与酒 2020-11-28 11:34

Is it possible to stop the Console.ReadLine() programmatically?

I have a console application: the much of the logic runs on a different thread and in th

10条回答
  •  猫巷女王i
    2020-11-28 11:54

    Send [enter] to the currently running console app:

        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.\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();
            }
        }
    

    This code sends [enter] into the current console process, aborting any ReadLine() calls blocking in unmanaged code deep within the windows kernel, which allows the C# thread to exit naturally.

    I used this code instead of the answer that involves closing the console, because closing the console means that ReadLine() and ReadKey() are permanently disabled from that point on in the code (it will throw an exception if its used).

    This answer is superior to all solutions that involve SendKeys and Windows Input Simulator, as it works even if the current app does not have the focus.

提交回复
热议问题