.NET调用send [进入]键击到当前的进程,这是一个控制台应用程序?这是一个、控制台、应用程序、进程

由网友(在月亮上罚站)分享简介:有没有办法捅[进入]键击到当前的进程,强制线程阻塞到Console.ReadLine()退出?Is there a way to poke the [enter] keystroke into the current process, to force the thread blocking on Console.R...

有没有办法捅[进入]键击到当前的进程,强制线程阻塞到Console.ReadLine()退出?

Is there a way to poke the [enter] keystroke into the current process, to force the thread blocking on Console.ReadLine() to exit?

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

我有一个正在运行的另一个线程被阻塞到Console.ReadLine()一个C#控制台应用程序。由于到Console.ReadLine调用运行深藏在Windows中的非托管code肠子本机Windows线程,它不会中止,直到放开,这将不会发生,直到它接收到的一个关键preSS键盘。

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.

因此​​,当我呼吁这个线程.Abort,在C#.NET,也不会约,直到我手动preSS [进入]在控制台上。我想自动完成这个关键的preSS。

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.

推荐答案

使用PostMessage的发送[进入]到当前进程:

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

这答案也适用回避的事实,调用 .Abort 的ReadLine()将不会在C#中工作,因为的ReadLine()在非托管code系列在Windows内核中运行。

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.

这答案是优于任何答案,只有工作,如果当前进程的重点,如的的SendKeys 和输入模拟器。

This answer is superior to any answers that only work if the current process has the focus, such as SendKeys and Input Simulator.

阅读全文

相关推荐

最新文章