打开一个应用程序,然后以编程方式单击该应用程序中的一个按钮

时间:2018-06-26 08:01:58

标签: c# .net winforms button

我想打开一个应用程序,然后单击该应用程序中的一个按钮,例如,我正在打开Microsoft Paint,然后尝试单击具有存储桶图像的“用颜色填充”按钮。

enter image description here

我只输入了流程的起始代码,不知道从哪里开始

designTime

1 个答案:

答案 0 :(得分:2)

您可以使用UI Automation API。

在下面的示例中,我假设有一个mspaint的打开实例,然后我发现了Fill with color按钮并单击了它。结果,您将看到工具栏按钮将被选中。

为此,请添加对UIAutomationClientUIAutomationTypes程序集的引用并添加using System.Windows.Automation;,然后使用以下代码:

var paint = System.Diagnostics.Process.GetProcessesByName("mspaint")
                    .FirstOrDefault();
if (paint != null)
{
    var paintMainWindow = paint.MainWindowHandle;
    var root = AutomationElement.FromHandle(paintMainWindow);
    var fillButton = root.FindAll(TreeScope.Subtree, Condition.TrueCondition)
        .Cast<AutomationElement>()
        .Where(x => x.Current.Name == "Fill with color").FirstOrDefault();
    if (fillButton != null)
    {
        var invokePattern = fillButton.GetCurrentPattern(InvokePattern.Pattern);
        if (invokePattern != null)
            ((InvokePattern)invokePattern).Invoke();
    }
}