How to interrupt Console.ReadLine

后端 未结 10 812
情歌与酒
情歌与酒 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条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 11:59

    This is a modified version of Contango's answer. Instead of using the current process's MainWindowhandle, this code uses GetForegroundWindow() to get the Console's MainWindowHandle if launched from cmd.

    using System;
    using System.Runtime.InteropServices;
    
    public class Temp
    {
        //Just need this
        //==============================
        static IntPtr ConsoleWindowHnd = GetForegroundWindow();
        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();
        [DllImport("User32.Dll")]
        private static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
        const int VK_RETURN = 0x0D;
        const int WM_KEYDOWN = 0x100;
        //==============================
    
        public static void Main(string[] args)
        {
            System.Threading.Tasks.Task.Run(() =>
            {
                System.Threading.Thread.Sleep(2000);
    
                //And use like this
                //===================================================
                PostMessage(ConsoleWindowHnd, WM_KEYDOWN, VK_RETURN, 0);
                //===================================================
    
            });
            Console.WriteLine("Waiting");
            Console.ReadLine();
            Console.WriteLine("Waiting Done");
            Console.Write("Press any key to continue . . .");
            Console.ReadKey();
        }
    }
    

    Optional

    Check to see if the foreground window was cmd. If it wasn't, then the current process should launch the console window so go ahead and use that. This shouldn't matter because the foreground window should be the current process window anyway, but this helps you feel good about it by double checking.

        int id;
        GetWindowThreadProcessId(ConsoleWindowHnd, out id);
        if (System.Diagnostics.Process.GetProcessById(id).ProcessName != "cmd")
        {
            ConsoleWindowHnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
        }
    

提交回复
热议问题