How can I send the F4 key to a process in C#? [dup

2019-01-19 00:24发布

问题:

This question already has an answer here:

  • Simulating Key Press c# 7 answers

I am starting a process from a Windows application. When I press a button I want to simulate the pressing of key F4 in that process. How can I do that?

[Later edit] I don't want to simulate the pressing of the F4 key in my form, but in the process I started.

回答1:

To send the F4 key to another process you will have to activate that process

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

  1. Get Process class instance returned by Process.Start
  2. Query Process.MainWindowHandle
  3. Call unmanaged Win32 API function "ShowWindow" or "SwitchToThisWindow"

You may then be able to use System.Windows.Forms.SendKeys.Send("{F4}") as Reed suggested to send the keystrokes to this process

EDIT:

The code example below runs notepad and sends "ABC" to it:

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


回答2:

You can use System.Windows.Forms.SendKeys.Send("{F4}");



回答3:

You can focus the window (SetForegroundWindow WINAPI), and then use windows forms SendKeys to send F4.