Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

c# - .NET call to send [enter] keystroke into the current process, which is a console app?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use PostMessage to send [enter] into the current process:

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.
");

        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.
");
        Console.Write("[any key to exit]");
        Console.ReadKey();
    }
}

This answer also works around the fact that calling .Abort on ReadLine() won't work in C#, as ReadLine() 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...