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

时间:2009-05-05 16:08:50

标签: c# process keyboard key

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

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

3 个答案:

答案 0 :(得分:11)

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

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

  1. 获取Process.Start返回的Process类实例
  2. 查询Process.MainWindowHandle
  3. 调用非托管Win32 API函数“ShowWindow”或“SwitchToThisWindow”
  4. 然后,您可以使用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");
                }
        }
    }
    

答案 1 :(得分:10)

答案 2 :(得分:1)

您可以关注窗口(SetForegroundWindow WINAPI),然后使用Windows窗体SendKeys发送F4。