使用UI Automation实现自动化测试--4.5 (WindowPattern)
WindowPattern
WindowPattern 控件模式用于支持在传统的 图形用户界面 (GUI) 内提供基于基本窗口的功能的控件。必须实现此控件模式的控件的示例包括顶级应用程序窗口、多文档界面 (MDI) 子窗口、大小可调的拆分窗格控件、模式对话框以及气球状帮助窗口。可以使用WindowPattern来对window进行操作,例如验证window是否激活,是否最大化、最小化、正常模式以及关闭window等。
下面的代码演示了WindowPattern的使用方法:
1
using System;2
using System.Text;3
using System.Diagnostics;4
using System.Threading;5
using System.Windows.Automation;6

7
namespace UIATest8


{9
class Program10

{11
static void Main(string[] args)12

{13
Process process = Process.Start(@"F:\CSharpDotNet\AutomationTest\ATP\WpfApp\bin\Debug\WpfApp.exe");14
int processId = process.Id;15
AutomationElement element = FindWindowByProcessId(processId);16
WindowPattern currentPattern = GetWindowPattern(element);17
18
//Set window visual state to Maximized19
currentPattern.SetWindowVisualState(WindowVisualState.Maximized);20
Thread.Sleep(1000);21

22
//Set window visual state to Normal23
currentPattern.SetWindowVisualState(WindowVisualState.Normal);24
Thread.Sleep(1000);25

26
//Set window visual state to Minimized27
currentPattern.SetWindowVisualState(WindowVisualState.Minimized);28
29
//Close window30
currentPattern.Close(); 31
}32

33

/**//// <summary>34
/// Get the automation elemention of current form.35
/// </summary>36
/// <param name="processId">Process Id</param>37
/// <returns>Target element</returns>38
public static AutomationElement FindWindowByProcessId(int processId)39

{40
AutomationElement targetWindow = null;41
int count = 0;42
try43

{44
Process p = Process.GetProcessById(processId);45
targetWindow = AutomationElement.FromHandle(p.MainWindowHandle);46
return targetWindow;47
}48
catch (Exception ex)49

{50
count++;51
StringBuilder sb = new StringBuilder();52
string message = sb.AppendLine(string.Format("Target window is not existing.try #{0}", count)).ToString();53
if (count > 5)54

{55
throw new InvalidProgramException(message, ex);56
}57
else58

{59
return FindWindowByProcessId(processId);60
}61
}62
}63

64

WindowPattern helper#region WindowPattern helper65

66

/**//// <summary>67
/// Get WindowPattern68
/// </summary>69
/// <param name="element">AutomationElement instance</param>70
/// <returns>WindowPattern instance</returns>71
public static WindowPattern GetWindowPattern(AutomationElement element)72

{73
object currentPattern;74
if (!element.TryGetCurrentPattern(WindowPattern.Pattern, out currentPattern))75

{76
throw new Exception(string.Format("Element with AutomationId '{0}' and Name '{1}' does not support the WindowPattern.",77
element.Current.AutomationId, element.Current.Name));78
}79
return currentPattern as WindowPattern;80
}81

82
#endregion83
}84
}85

本文简单介绍了WindowPattern以及WindowPattern在测试中的使用方法。


浙公网安备 33010602011771号