【问题标题】:How can I send keypresses to a running process object?如何将按键发送到正在运行的进程对象?
【发布时间】:2011-02-10 19:50:19
【问题描述】:

我正在尝试让 C# 启动一个应用程序(在本例中为开放式办公室),并开始发送该应用程序按键,这样就好像有人在打字一样。所以理想情况下,我可以发送一个正在运行的开放式办公进程,按下字母“d”的按键,然后开放式办公会在纸上输入 d。任何人都可以按照如何去做这件事给我指导吗?我已尝试执行以下操作:

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

p.Start();

p.StandardInput.Write("hello");

但这并没有达到我想要的效果 - 我没有看到在开放式办公室中输入的文本。

【问题讨论】:

  • 我知道您要求使用 C#,但您可能想看看 AutoHotkey。即使您不能将它用于这个特定的问题,它也是一个很好的工具来记住这种类型的任务。
  • 这不是上述问题的重复,因为他的目标窗口不是.Net应用程序。

标签: c# .net process input keyboard


【解决方案1】:

你必须通过 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 做到了这一点。

    我将它用于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);
            }
        }
    }
    

    这个可以这么简单的使用。

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

    【讨论】:

    • 非GUI窗口呢?
    • 类似问题中提供的答案可能就是您正在寻找的。 stackoverflow.com/a/8629216/11870
    • 不,你需要使用StartInfo.RedirectStandardInputproc.StandardInput.WriteLine("S")
    猜你喜欢
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    相关资源
    最近更新 更多