如何通过C#向应用程序UI自动化发送按键输入

3

我需要找到键盘按键的自动化ID。如何通过UI自动化向应用程序发送按键击?我需要自动化页面向上和向下键的功能。最佳方法是什么?

编辑: 在我的应用程序中,以下是流程。假设最终用户打开具有5个页面的MS Word文档,并按Page Up和Page Down按钮在这些页面之间移动。我想使用C#自动化此场景。目前我已经使用了UIAutomationClient.dll和UIAutomationTypes.dll。我能使用它们吗?


1
@Sirwani与此无关。他想在外部应用程序上模拟按键。 - SimpleVar
尝试使用WinApi调用SetForegroundWindow和SendKeys的组合。 - SimpleVar
我已经尝试过这个。但是我需要自动化ID才能使用它。http://www.scip.be/index.php?Page=ArticlesNET20&Lang=EN - DevT
@YoryeNathan 我需要自动化。我已经编辑了我的问题。请查看。谢谢 - DevT
1
不太确定您是指按键(即模拟键盘上的按键)还是按钮点击(即模拟使用鼠标在按钮上单击)。对于前者,您不需要AutomationId,对于后者,这是一种方法-因为对于鼠标单击,您将需要屏幕坐标,然后可以使用您获得的AutomationElement的ClickablePoint。对于前者,请使用SendKeys.Send。 - Andreas Reiff
6个回答

4

自动发送各种按键的一个很好的方式是使用AutoIt自动化和脚本语言。可以做很多事情,特别是向上翻页和向下翻页。

我建议使用autoit编写一个exe文件,并将其连接到需要发送按键的程序中。


AutoIt可以做到这一点!但不需要C#,因为您可以单独编译AutoIt脚本。而且您可以在C#中使用它...但这并非必需。 - Mare Infinitus

4
  1. 使用P/Invoke激活应用程序窗口。
  2. 使用任何字符调用SendWait("C")

例如:

// Get a handle to an application window.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

// Send a series of key presses to the Calculator application. 
private void button1_Click(object sender, EventArgs e)
 {
    // Get a handle to the Calculator application. The window class 
    // and window name were obtained using the Spy++ tool.
    IntPtr calculatorHandle = FindWindow("CalcFrame","Calculator");

    // Verify that Calculator is a running process. 
    if (calculatorHandle == IntPtr.Zero)
    {
        MessageBox.Show("Calculator is not running.");
        return;
    }

    // Make Calculator the foreground application and send it  
    // a set of calculations.
    SetForegroundWindow(calculatorHandle);
    SendKeys.SendWait("111");
    SendKeys.SendWait("*");
    SendKeys.SendWait("11");
    SendKeys.SendWait("=");
}

请参阅如何在代码中模拟鼠标和键盘事件>“向不同应用程序发送按键”。


1
有时,在调用SetForegroundWindow之后,发送按键之前使用Thread.Sleep(100)添加时间延迟会很有用。 - Hassan Rahman

1

我想你想要向一个没有源代码的应用程序发送按键。
我无法直接告诉你如何在C#中完成它。
但是你可以使用AutoIt轻松地完成它;它有一个DLL,你可以在C#中引用它来完成你需要的操作。


1

1

1
请发布构造的答案,然后提供参考资料。 - Sachith Muhandiram

0
在这种场景下,将Word文档置于前台,然后使用屏幕键盘
System.Diagnostics.Process.Start("osk.exe");并使用鼠标输入点击页面上下按钮
因为对于鼠标点击需要页面上下按钮的屏幕坐标。
(我曾尝试使用UI自动化检测屏幕键盘,但它无法检测到屏幕上的按键。https://stackoverflow.com/questions/11077738/windows-sdk-inspect-tool-what-are-the-reasons-on-screen-keyboard-does-not-disp 找不到解决办法。因此,我使用此移动单击方法来单击该按钮。)

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