如何向正在运行的进程对象发送按键?

5

我正在尝试使用C#启动一个应用程序(在这种情况下是OpenOffice),并开始发送该应用程序的按键,以便它看起来像有人在打字。因此,理想情况下,我将能够为正在运行的OpenOffice进程发送按键“d”,然后OpenOffice会在文档中输入d。有谁能指导我如何做到这一点?我已经尝试了以下操作:

p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.FileName = processNames.executableName;

p.Start();

p.StandardInput.Write("hello");

但这并不能达到我想要的效果——我在Open Office中看不到输入的文本。

可能是重复的问题,与https://dev59.com/gkjSa4cB1Zd3GeqPCA_t相同。 - Preet Sangha
我知道你要求使用C#,但你可能想看看AutoHotkey。即使你不能用它来解决这个具体的问题,它也是一个值得记住的处理此类任务的好工具。 - NickAldwin
这不是上面问题的重复,因为他的目标窗口不是 .Net 应用程序。 - Foxfire
2个回答

4
你需要通过Win32 sendmessages来完成这个操作:基本思路如下:
首先,你需要获取已启动进程窗口的指针:
using System.Runtime.InteropServices;

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

private void button1_Click(object sender, EventArgs e)
{
  // Find a window with the name "Test Application"
  IntPtr hwnd = FindWindow(null, "Test Application");
}

然后使用SendMessage或PostMessage(我猜在您的情况下更喜欢后者):

http://msdn.microsoft.com/en-us/library/ms644944(v=VS.85).aspx

在此消息中指定正确的消息类型(例如WM_KEYDOWN)以发送按键:

http://msdn.microsoft.com/en-us/library/ms646280(VS.85).aspx

请查看PInvoke.net,以获取PInvoke源代码。
或者,在使用FindWindow将窗口置于前景后,可以使用SendKeys.Send (.Net)方法。然而,这种方法有一定的不可靠性。

2
我使用了SetForegroundWindow和SendKeys来实现此功能。 我在这里使用了它。
[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);
        }
    }
}

这可以非常简单地使用。
Process p = Process.Start("notepad.exe");
SendText(p.MainWindowHandle, "Hello, world");

非 GUI 窗口怎么办? - Toolkit
在类似问题中提供的答案可能是您正在寻找的答案。https://dev59.com/rV7Va4cB1Zd3GeqPLZ_a#8629216 - Cory
不行,你需要使用 StartInfo.RedirectStandardInputproc.StandardInput.WriteLine("S") - Toolkit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接