Метод вызова не работает в диалоговом окне открытия окна - PullRequest
0 голосов
/ 20 сентября 2019

Я пытался сделать некоторую автоматизацию с помощью автоматизации пользовательского интерфейса Microsoft с C #, и на первом шаге я попытался сделать некоторую автоматизацию с помощью блокнота.То, что я пытался добиться этого, чтобы запустить блокнот и открыть текстовый файл из случайного места.

Что я уже достиг:

  • Открыть блокнот
  • Вызвать (развернуть) файловое меню и Вызвать (щелкнуть) кнопку «Открыть ...».
  • Запишите путь к имени файла в текстовое поле «Имя файла» всплывающего диалогового окна «Открыть» (как ни странно, яне в состоянии вызвать действие щелчка на адресной строке, но справиться с этим, это будет следующая задача).

Program.cs

using System;
using System.Linq;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Windows.Automation;
using System.Runtime.InteropServices;


namespace TestUIAutomation
{

    class Program
    {

        [DllImport("user32.dll")]
        public static extern int SetForegroundWindow(IntPtr hWnd);
static void Main(string[] args)
{
    Process p = Process.Start(@"notepad.exe");
    SetForegroundWindow(p.MainWindowHandle);

    Thread.Sleep(1000);

    var baseSoftware = AutomationElement.RootElement.FindFirst(TreeScope.Children, new 
    PropertyCondition(AutomationElement.NameProperty, "Untitled - Notepad"));

    var fileButton = baseSoftware.FindFirst(TreeScope.Descendants, new 
    propertyCondition(AutomationElement.NameProperty, "File"));

    var fileButtonExpand = Utilitiy.ExCoPattern(fileButton);

    if (fileButtonExpand.Current.ExpandCollapseState != ExpandCollapseState.Expanded)
            {
                fileButtonExpand.Expand();
            }

    var openButton = baseSoftware.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Open..."));
            Utilitiy.GetInvokePattern(openButton).Invoke();

    Thread.Sleep(1000);

    var addressBar = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "File name:"));

    SendKeys.SendWait(@"C:\Users\user1\Documents\Test.txt");

    var findOpenButton = new AndCondition(new PropertyCondition(AutomationElement.NameProperty, "Open"), new PropertyCondition(AutomationElement.AutomationIdProperty, "1"));


    var openButtonDialog = AutomationElement.RootElement.FindFirst(TreeScope.Descendants, findOpenButton);

    Utilitiy.GetInvokePattern(openButtonDialog);
}
}
}

Утилита cs

using System;
using System.Windows.Automation;

namespace TestUIAutomation
{
    class Utilitiy
    {
        public static void SetCombobValueByUIA(AutomationElement ctrl, string newValue)
        {
            ExpandCollapsePattern exPat = ctrl.GetCurrentPattern(ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;

            if (exPat == null)
            {
                throw new ApplicationException("Bad Control type...");
            }

            exPat.Expand();

            AutomationElement itemToSelect = ctrl.FindFirst(TreeScope.Descendants, new
                                  PropertyCondition(AutomationElement.NameProperty, newValue));

            SelectionItemPattern sPat = itemToSelect.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
            sPat.Select();            
        }
        public static InvokePattern GetInvokePattern(AutomationElement element)
        {
            return element.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
        }
        public static TogglePattern CheckBoxPattern(AutomationElement element)
        {
            return element.GetCurrentPattern(TogglePattern.Pattern) as TogglePattern;
        }
        public static SelectionItemPattern RadioButtonPattern(AutomationElement element)
        {
            return element.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
        }
        public static ValuePattern TextValuePattern(AutomationElement element)
        {
            return element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
        }
        public static ExpandCollapsePattern ExCoPattern(AutomationElement element)
        {
            return element.GetCurrentPattern(ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
        }
    }
}

Проблема в настоящее время, я не получаю никаких сообщений об ошибках, поэтому программа фактически вызывает кнопку открытия, но в реальной жизни ничего не происходит.Я могу использовать метод sendkeys для ввода ввода, чтобы открыть файл, но если это возможно, я бы хотел вызвать кнопку открытия.

1 Ответ

0 голосов
/ 20 сентября 2019

Хорошо, я нашел решение, я забыл, чтобы вызвать кнопку.

Я изменяю последнюю строку с этой

Utilitiy.GetInvokePattern(openButtonDialog);

На эту

Utilitiy.GetInvokePattern(openButtonDialog).Invoke();
...