【问题标题】:Open an application and then click a button in that application programmatically打开应用程序,然后以编程方式单击该应用程序中的按钮
【发布时间】:2018-06-26 08:01:58
【问题描述】:

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

我只放了流程启动代码,不知道从哪里开始

public partial class Form1 : Form
{
    public Process P;
    public IntPtr WindowHandle;
    public Image TargetButton;

    public Form1()
    {
        InitializeComponent();

        Init();
    }

    private void Init()
    {
        TargetButton = Bitmap.FromFile("Bucket.JPG");

        P = Process.Start("C:\\Windows\\System32\\mspaint.exe");
        WindowHandle = P.MainWindowHandle;

        // now to find that button and click it, I have the button stored as image in TargetButton variable above
    }
}

【问题讨论】:

    标签: c# .net winforms button


    【解决方案1】:

    您可以使用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();
        }
    }
    

    【讨论】:

    • Paint 只是一个例子。 OP 正在寻找一个通用的解决方案。
    • @PepitoSh 当 OP 接受答案时,这意味着答案非常令人满意。
    • 很满足,好吧。我建议对 OP 进行编辑,以反映特定解决方案如何解决一般问题。
    • @PepitoSh 如果您熟悉 UI 自动化,那么答案就是展示如何查找元素以及如何单击它。我可以说,这是一个很好的答案,虽然它不会是一个普遍的答案,但它已经足够普遍了。
    • @PepitoSh 我注意到你在被否决后删除了你的答案。否决您也试图回答的问题,这不是一个好主意。 JFYI我不是你的答案的反对者,我只是从反对你的答案的同一个人那里得到了反对。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多