如何将F4密钥发送到C#中的进程?

Ste*_*lip 9 c# keyboard key process

我正在从Windows应用程序启动一个进程.当我按下按钮时,我想F4在该过程中模拟按键.我怎样才能做到这一点?

[稍后编辑]我不想F4在我的表单中模拟按键,但在此过程中我开始了.

Pat*_*ald 11

要将F4密钥发送到另一个进程,您必须激活该进程

http://bytes.com/groups/net-c/230693-activate-other-process建议:

  1. 获取Process.Start返回的Process类实例
  2. 查询Process.MainWindowHandle
  3. 调用非托管Win32 API函数"ShowWindow"或"SwitchToThisWindow"

然后,您可以使用System.Windows.Forms.SendKeys.Send("{F4}"),因为Reed建议将按键发送到此进程

编辑:

下面的代码示例运行记事本并向其发送"ABC":

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace TextSendKeys
{
    class Program
    {
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        static void Main(string[] args)
            {
                Process notepad = new Process();
                notepad.StartInfo.FileName = @"C:\Windows\Notepad.exe";
                notepad.Start();

                // Need to wait for notepad to start
                notepad.WaitForInputIdle();

                IntPtr p = notepad.MainWindowHandle;
                ShowWindow(p, 1);
                SendKeys.SendWait("ABC");
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用notepad.WaitForInputIdle()来避免睡眠 - 这样它可以在你以外的机器上工作:-) (2认同)
  • 我在WinForms应用程序中使用此方法,但发现SendWait(和Send)似乎只工作一次.我从按钮单击事件处理程序调用发送代码. (2认同)