How can I send keypresses to a running process object?

前端 未结 2 1687
灰色年华
灰色年华 2020-12-03 19:53

I am trying to make C# launch an application (in this case open office), and start sending that application keypresses such that it would appear as though someone is typing.

2条回答
  •  独厮守ぢ
    2020-12-03 20:10

    I did this using SetForegroundWindow and SendKeys.

    I used it for this.

    [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool SetForegroundWindow(IntPtr hWnd);
    
    public void SendText(IntPtr hwnd, string keys)
    {
        if (hwnd != IntPtr.Zero)
        {
            if (SetForegroundWindow(hwnd))
            {
                System.Windows.Forms.SendKeys.SendWait(keys);
            }
        }
    }
    

    This can be used as simply as this.

    Process p = Process.Start("notepad.exe");
    SendText(p.MainWindowHandle, "Hello, world");
    

提交回复
热议问题