How to use launchUIAutomationServer method in fMBT

Best Python code snippet using fMBT_python

fmbtwindows_agent.py

Source:fmbtwindows_agent.py Github

copy

Full Screen

...798 ctypes.c_void_p)799 cb = EnumChildProc(enumChildProc)800 ctypes.windll.user32.EnumChildWindows(hwnd, cb, hwnd)801 return widgets802def launchUIAutomationServer():803 fromPath=[]804 properties=[]805 powershellCode = r"""806$assemblies = ('System', 'UIAutomationTypes', 'UIAutomationClient')807$source = @'808using System;809using System.Collections.Generic;810using System.IO;811using System.IO.Pipes;812using System.Linq;813using System.Windows.Automation;814namespace FmbtWindows815{816 public class UI817 {818 // Common variables, shared by all requests.819 private static Dictionary<string, TreeWalker> stringToTreeWalker;820 private static Dictionary<string, AutomationProperty> stringToAutomationProperty;821 private static StreamWriter outStream;822 private static Dictionary<long, AutomationElement> elements;823 private static Dictionary<long, long> parents;824 private static bool cacheElements;825 private static string cacheMode;826 private static IntPtr lastWindow;827 // A static constructor is a nicer way to initialize static fields, when there's complicated code.828 static UI()829 {830 stringToTreeWalker = new Dictionary<string, TreeWalker> {831 { "raw", TreeWalker.RawViewWalker },832 { "control", TreeWalker.ControlViewWalker },833 { "content", TreeWalker.ContentViewWalker },834 };835 stringToAutomationProperty = new Dictionary<string, AutomationProperty>836 {837 { "AcceleratorKey", AutomationElement.AcceleratorKeyProperty},838 { "AccessKey", AutomationElement.AccessKeyProperty},839 { "AutomationId", AutomationElement.AutomationIdProperty},840 { "BoundingRectangle", AutomationElement.BoundingRectangleProperty},841 { "CanSelectMultiple", SelectionPattern.CanSelectMultipleProperty},842 { "ClassName", AutomationElement.ClassNameProperty},843 { "ControlType", AutomationElement.ControlTypeProperty},844 { "CultureProperty", AutomationElement.CultureProperty},845 { "ExpandCollapseState", ExpandCollapsePattern.ExpandCollapseStateProperty},846 { "FrameworkId", AutomationElement.FrameworkIdProperty},847 { "HasKeyboardFocus", AutomationElement.HasKeyboardFocusProperty},848 { "HelpText", AutomationElement.HelpTextProperty},849 { "HorizontalScrollPercent", ScrollPattern.HorizontalScrollPercentProperty},850 { "HorizontalViewSize", ScrollPattern.HorizontalViewSizeProperty},851 { "HorizontallyScrollable", ScrollPattern.HorizontallyScrollableProperty},852 { "IsContentElement", AutomationElement.IsContentElementProperty},853 { "IsControlElement", AutomationElement.IsControlElementProperty},854 { "IsDockPatternAvailable", AutomationElement.IsDockPatternAvailableProperty},855 { "IsEnabled", AutomationElement.IsEnabledProperty},856 { "IsGridItemPatternAvailable", AutomationElement.IsGridItemPatternAvailableProperty},857 { "IsGridPatternAvailable", AutomationElement.IsGridPatternAvailableProperty},858 { "IsInvokePatternAvailable", AutomationElement.IsInvokePatternAvailableProperty},859 { "IsItemContainerPatternAvailable", AutomationElement.IsItemContainerPatternAvailableProperty},860 { "IsKeyboardFocusable", AutomationElement.IsKeyboardFocusableProperty},861 { "IsMultipleViewPatternAvailable", AutomationElement.IsMultipleViewPatternAvailableProperty},862 { "IsOffscreen", AutomationElement.IsOffscreenProperty},863 { "IsPassword", AutomationElement.IsPasswordProperty},864 { "IsRangeValuePatternAvailable", AutomationElement.IsRangeValuePatternAvailableProperty},865 { "IsReadOnly", ValuePattern.IsReadOnlyProperty},866 { "IsScrollItemPatternAvailable", AutomationElement.IsScrollItemPatternAvailableProperty},867 { "IsScrollPatternAvailable", AutomationElement.IsScrollPatternAvailableProperty},868 { "IsSelectionItemPatternAvailable", AutomationElement.IsSelectionItemPatternAvailableProperty},869 { "IsSelectionPatternAvailable", AutomationElement.IsSelectionPatternAvailableProperty},870 { "IsSelectionRequired", SelectionPattern.IsSelectionRequiredProperty},871 { "IsSynchronizedInputPatternAvailable", AutomationElement.IsSynchronizedInputPatternAvailableProperty},872 { "IsTableItemPatternAvailable", AutomationElement.IsTableItemPatternAvailableProperty},873 { "IsTablePatternAvailable", AutomationElement.IsTablePatternAvailableProperty},874 { "IsTextPatternAvailable", AutomationElement.IsTextPatternAvailableProperty},875 { "IsTogglePatternAvailable", AutomationElement.IsTogglePatternAvailableProperty},876 { "IsTransformPatternAvailable", AutomationElement.IsTransformPatternAvailableProperty},877 { "IsValuePatternAvailable", AutomationElement.IsValuePatternAvailableProperty},878 { "IsVirtualizedItemPatternAvailable", AutomationElement.IsVirtualizedItemPatternAvailableProperty},879 { "IsWindowPatternAvailable", AutomationElement.IsWindowPatternAvailableProperty},880 { "ItemStatus", AutomationElement.ItemStatusProperty},881 { "ItemType", AutomationElement.ItemTypeProperty},882 { "LabeledBy", AutomationElement.LabeledByProperty},883 { "LocalizedControlType", AutomationElement.LocalizedControlTypeProperty},884 { "Name", AutomationElement.NameProperty},885 { "Orientation", AutomationElement.OrientationProperty},886 { "ProcessId", AutomationElement.ProcessIdProperty},887 { "RuntimeId", AutomationElement.RuntimeIdProperty},888 { "Selection", SelectionPattern.SelectionProperty},889 { "ToggleState", TogglePattern.ToggleStateProperty},890 { "Value", ValuePattern.ValueProperty},891 { "VerticalViewSize", ScrollPattern.VerticalViewSizeProperty},892 { "VerticallyScrollable", ScrollPattern.VerticallyScrollableProperty},893 };894 elements = new Dictionary<long, AutomationElement>();895 parents = new Dictionary<long, long>();896 cacheElements = true;897 cacheMode = "lastwindow"; // It can only be: "none", "lastdump", "lastwindow", "all"898 lastWindow = new IntPtr(0);899 }900 private static int ReportFail(string message)901 {902 outStream.Write("\0!" + message + '\0');903 return -1;904 }905 private static void DumpElementProperties(AutomationElement elt, AutomationProperty[] supportedProps, string[] properties = null)906 {907 foreach (var p in supportedProps)908 {909 var pName = p.ProgrammaticName.Substring(p.ProgrammaticName.IndexOf(".") + 1);910 if (pName.EndsWith("Property"))911 {912 pName = pName.Substring(0, pName.LastIndexOf("Property"));913 if (properties == null || properties.Length == 1 || (properties.Length > 1 && properties.Contains(pName)))914 {915 var pValue = "" + elt.GetCurrentPropertyValue(p);916 outStream.Write(pName + "=" + pValue.Replace("\\", "\\\\").Replace("\r\n", "\\r\\n") + '\0');917 }918 }919 }920 }921 public static void DumpElementInfo(AutomationElement elt, long eltHash, int depth, long parent, long[] fromPath, string[] properties, int[] bbox,922 string dumpChildClass, string dumpChildName, bool doNotDump)923 {924 string pValue;925 string pName;926 var supportedProps = elt.GetSupportedProperties();927 // If location filtering is requested, skip element after reading only BoundingRectangle928 if (bbox[0] > -1)929 {930 foreach (var p in supportedProps)931 {932 pName = p.ProgrammaticName.Substring(p.ProgrammaticName.IndexOf(".") + 1);933 if (pName == "BoundingRectangleProperty")934 {935 int eltLeft, eltTop, eltRight, eltBottom;936 pValue = "" + elt.GetCurrentPropertyValue(p);937 if (pValue.Contains(";"))938 {939 var bRect = Array.ConvertAll(pValue.Split(';'), int.Parse);940 eltLeft = bRect[0]; eltTop = bRect[1];941 eltRight = bRect[0] + bRect[2]; eltBottom = bRect[1] + bRect[3];942 }943 else if (pValue.Contains(","))944 {945 var bRect = Array.ConvertAll(pValue.Split(','), int.Parse);946 eltLeft = bRect[0]; eltTop = bRect[1];947 eltRight = bRect[0] + bRect[2]; eltBottom = bRect[1] + bRect[3];948 }949 else {950 continue;951 }952 if (eltRight < bbox[0] || eltLeft > bbox[2] || eltBottom < bbox[1] || eltTop > bbox[3])953 {954 return; // Skip this element and its descendants955 }956 break; // Skip all other properties, since we have nothing else to check.957 }958 }959 }960 // Print element properties, if dump is allowed and child conditions are satified (if any).961 var dump = !doNotDump;962 if (dump && dumpChildClass != "")963 {964 var className = elt.GetCurrentPropertyValue(AutomationElement.ClassNameProperty, true);965 dump = className != AutomationElement.NotSupported && (className as string) == dumpChildClass;966 }967 if (dump && dumpChildName != "")968 {969 var name = elt.GetCurrentPropertyValue(AutomationElement.NameProperty, true);970 dump = name != AutomationElement.NotSupported && (name as string) == dumpChildName;971 }972 if (dump)973 {974 outStream.Write('\0');975 outStream.Write("hash=" + eltHash.ToString() + '\0');976 outStream.Write("parent=" + parent.ToString() + '\0');977 DumpElementProperties(elt, supportedProps, properties);978 }979 if (cacheElements)980 {981 elements[eltHash] = elt;982 parents[eltHash] = parent;983 }984 }985 public static void DumpElement(AutomationElement elt, int depth, long parent, long[] fromPath, string[] properties, int[] bbox, TreeWalker walker,986 string dumpChildClass, string dumpChildName, bool doNotDump)987 {988 long eltHash = elt.GetHashCode();989 eltHash = (parent << 32) + eltHash;990 if (fromPath.Length > depth && fromPath[depth] != eltHash)991 {992 return;993 }994 DumpElementInfo(elt, eltHash, depth, parent, fromPath, properties, bbox, dumpChildClass, dumpChildName, doNotDump);995 // Print child elements996 var eltChild = walker.GetFirstChild(elt);997 while (eltChild != null)998 {999 DumpElement(eltChild, depth + 1, eltHash, fromPath, properties, bbox, walker, dumpChildClass, dumpChildName, doNotDump);1000 eltChild = walker.GetNextSibling(eltChild);1001 }1002 }1003 public static int DumpWindow(string hwndString, string fromPathString, string properties, string bboxString, string walkerString,1004 string filterType, string filterCondition, string dumpChildClass, string dumpChildName, string doNotDumpString)1005 {1006 var hwnd = new IntPtr(UInt32.Parse(hwndString));1007 if (cacheMode == "none" || cacheMode == "lastdump" || ((cacheMode == "lastwindow") && (lastWindow != hwnd)))1008 {1009 ClearCache();1010 }1011 lastWindow = hwnd;1012 var fromPath = Array.ConvertAll(fromPathString.Split(','), long.Parse);1013 var bbox = Array.ConvertAll(bboxString.Split(','), int.Parse);1014 var doNotDump = bool.Parse(doNotDumpString.ToLower());1015 TreeWalker walker;1016 if (!stringToTreeWalker.TryGetValue(walkerString, out walker))1017 {1018 return ReportFail("Unknown walker: " + walker);1019 }1020 var windowElement = AutomationElement.FromHandle(hwnd);1021 var splittedProperties = properties.Split(',');1022 if (filterType == "none")1023 {1024 DumpElement(windowElement, 1, 0, fromPath, splittedProperties, bbox, walker, dumpChildClass, dumpChildName, doNotDump);1025 }1026 else1027 {1028 Condition condition = null;1029 string lastOperator = "";1030 var lastPosition = 0;1031 while (lastPosition < filterCondition.Length)1032 {1033 if (filterCondition[lastPosition] == ' ')1034 {1035 lastPosition++;1036 }1037 else if (filterCondition.IndexOf("and ", lastPosition) == lastPosition)1038 {1039 if (condition == null)1040 {1041 return ReportFail(String.Format("and operator found (around position {0}) without left argument in the filter condition: {1}", lastPosition, filterCondition));1042 }1043 lastOperator = "and";1044 lastPosition += 4;1045 }1046 else {1047 var position = filterCondition.IndexOf("==", lastPosition);1048 if (position < 0)1049 {1050 return ReportFail(String.Format("== operator not found (around position {0}) in the filter condition: {1}", lastPosition, filterCondition));1051 }1052 var propName = filterCondition.Substring(lastPosition, position - lastPosition).Trim();1053 AutomationProperty propertyField;1054 if (!stringToAutomationProperty.TryGetValue(propName, out propertyField))1055 {1056 return ReportFail(String.Format("Unknown property \"{0}\" (around position {1}) in the filter condition: {2}", propName, lastPosition, filterCondition));1057 }1058 lastPosition = filterCondition.IndexOf("\"", position + 2); ; // Skip ==, search first "1059 if (lastPosition < 0)1060 {1061 return ReportFail(String.Format("The value in the filter condition doesn't start with a double quote (around position {0}): {1}", position + 2, filterCondition));1062 }1063 position = filterCondition.IndexOf("\"", lastPosition + 1); ; // Skip the first ", search second one1064 if (position < 0)1065 {1066 return ReportFail(String.Format("The value in the filter condition doesn't end with a double quote (around position {0}): {1}", lastPosition + 1, filterCondition));1067 }1068 var propValue = filterCondition.Substring(lastPosition + 1, position - lastPosition - 1); // Skip double quotes1069 lastPosition = position + 1;1070 var new_condition = new PropertyCondition(propertyField, propValue);1071 if (lastOperator == "and")1072 {1073 lastOperator = "";1074 condition = new AndCondition(condition, new_condition);1075 }1076 else1077 {1078 condition = new_condition;1079 }1080 }1081 }1082 if (condition == null)1083 {1084 return ReportFail("Invalid condition: " + filterCondition);1085 }1086 AutomationElement finding = null;1087 AutomationElementCollection findings = null;1088 if (filterType.StartsWith("all"))1089 {1090 findings = windowElement.FindAll(TreeScope.Element | TreeScope.Descendants | TreeScope.Subtree, condition);1091 }1092 else if (filterType.StartsWith("first"))1093 {1094 finding = windowElement.FindFirst(TreeScope.Element | TreeScope.Descendants | TreeScope.Subtree, condition);1095 }1096 else1097 {1098 return ReportFail("Unknown filter type: " + filterType);1099 }1100 if (finding != null)1101 {1102 if (filterType.Contains("children"))1103 {1104 DumpElement(finding, 1, 0, fromPath, splittedProperties, bbox, walker, dumpChildClass, dumpChildName, doNotDump);1105 }1106 else1107 {1108 DumpElementInfo(finding, finding.GetHashCode(), 1, 0, fromPath, splittedProperties, bbox, dumpChildClass, dumpChildName, doNotDump);1109 }1110 }1111 if (findings != null)1112 {1113 if (filterType.Contains("children"))1114 {1115 foreach (AutomationElement elt in findings)1116 {1117 DumpElement(elt, 1, 0, fromPath, splittedProperties, bbox, walker, dumpChildClass, dumpChildName, doNotDump);1118 }1119 }1120 else1121 {1122 foreach (AutomationElement elt in findings)1123 {1124 DumpElementInfo(elt, elt.GetHashCode(), 1, 0, fromPath, splittedProperties, bbox, dumpChildClass, dumpChildName, doNotDump);1125 }1126 }1127 }1128 }1129 return 0;1130 }1131 // AutomationElement methods1132 private static bool GetElementFromHash(string eltHashString, out long eltHash, out AutomationElement elt)1133 {1134 eltHash = long.Parse(eltHashString);1135 if (!elements.TryGetValue(eltHash, out elt))1136 {1137 return ReportFail("Element not found: " + eltHash) != -1;1138 }1139 return true;1140 }1141 public static int DumpCachedElement(string eltHashString)1142 {1143 long eltHash;1144 AutomationElement elt;1145 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1146 return -1;1147 long parent = 0;1148 parents.TryGetValue(eltHash, out parent);1149 DumpElementInfo(elt, eltHash, 0, parent, new long[0], null, new int[] {-1, -1, -1, -1}, "", "", false);1150 return 0;1151 }1152 private static object GetPattern(AutomationElement elt, AutomationPattern patternType)1153 {1154 // For a list of supported patterns: https://msdn.microsoft.com/en-us/library/ms752056(v=vs.110).aspx1155 object pattern;1156 if (!elt.TryGetCurrentPattern(patternType, out pattern))1157 {1158 ReportFail("This element doesn't support the " + Automation.PatternName(patternType) + " pattern: " + elt.GetHashCode());1159 return null;1160 }1161 return pattern;1162 }1163 public static int GetProperties(string eltHashString)1164 {1165 long eltHash;1166 AutomationElement elt;1167 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1168 return -1;1169 DumpElementProperties(elt, elt.GetSupportedProperties());1170 return 0;1171 }1172 public static int GetPatterns(string eltHashString)1173 {1174 long eltHash;1175 AutomationElement elt;1176 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1177 return -1;1178 outStream.Write("[\0");1179 foreach (var pattern in elt.GetSupportedPatterns())1180 {1181 outStream.Write(Automation.PatternName(pattern) + '\0');1182 }1183 outStream.Write("]\0");1184 return 0;1185 }1186 public static int SetFocus(string eltHashString)1187 {1188 long eltHash;1189 AutomationElement elt;1190 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1191 return -1;1192 elt.SetFocus();1193 return 0;1194 }1195 private static void CollectAllTexts(AutomationElement elt, AutomationProperty propertyField,1196 string filterSubChildClassName, int maxSubChildren, List<string> texts, TreeWalker walker)1197 {1198 if (maxSubChildren != 0 && texts.Count >= maxSubChildren)1199 {1200 return;1201 }1202 if (filterSubChildClassName == "" || elt.Current.ClassName == filterSubChildClassName)1203 {1204 var value = elt.GetCurrentPropertyValue(propertyField, true);1205 if (value != AutomationElement.NotSupported)1206 {1207 texts.Add("" + value);1208 }1209 }1210 // Collect all child elements1211 var eltChild = walker.GetFirstChild(elt);1212 while (eltChild != null)1213 {1214 CollectAllTexts(eltChild, propertyField, filterSubChildClassName, maxSubChildren, texts, walker);1215 eltChild = walker.GetNextSibling(eltChild);1216 }1217 }1218 private static void CollectAllTextsCached(AutomationElement elt, AutomationProperty propertyField,1219 string filterSubChildClassName, int maxSubChildren, List<string> texts)1220 {1221 if (maxSubChildren != 0 && texts.Count >= maxSubChildren)1222 {1223 return;1224 }1225 if (filterSubChildClassName == "" || elt.Cached.ClassName == filterSubChildClassName)1226 {1227 var value = elt.GetCachedPropertyValue(propertyField, true);1228 if (value != AutomationElement.NotSupported) {1229 texts.Add("" + value);1230 }1231 }1232 // Collect all child elements1233 foreach (AutomationElement child in elt.CachedChildren)1234 {1235 CollectAllTextsCached(child, propertyField, filterSubChildClassName, maxSubChildren, texts);1236 }1237 }1238 public static int GetItems(string eltHashString, string propertyName, string separator,1239 string filterSubChildClassName, string maxSubChildrenString)1240 {1241 long eltHash;1242 AutomationElement elt;1243 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1244 return -1;1245 AutomationProperty propertyField;1246 if (!stringToAutomationProperty.TryGetValue(propertyName, out propertyField))1247 {1248 return ReportFail(String.Format("Unknown property: \"{0}\"", propertyName));1249 }1250 var maxSubChildren = int.Parse(maxSubChildrenString);1251 var cacheRequest = new CacheRequest();1252 cacheRequest.Add(propertyField);1253 if (filterSubChildClassName != "")1254 {1255 cacheRequest.Add(AutomationElement.ClassNameProperty);1256 }1257 cacheRequest.TreeScope = TreeScope.Element | TreeScope.Descendants | TreeScope.Subtree;1258 AutomationElement element;1259 using (cacheRequest.Activate())1260 {1261 // Load the element caching the specified properties for all its descendants.1262 var condition = new PropertyCondition(AutomationElement.ControlTypeProperty, elt.Current.ControlType);1263 element = elt.FindFirst(cacheRequest.TreeScope, condition);1264 if (element == null)1265 {1266 return ReportFail("Cannot find the element : " + eltHash);1267 }1268 }1269 var texts = new List<string>();1270 outStream.Write("[\0");1271 foreach (AutomationElement item in element.CachedChildren)1272 {1273 CollectAllTextsCached(item, propertyField, filterSubChildClassName, maxSubChildren, texts);1274 outStream.Write(String.Join(separator, texts) + '\0');1275 texts.Clear();1276 }1277 outStream.Write("]\0");1278 return 0;1279 }1280 // ExpandCollapsePattern methods1281 public static int Collapse(string eltHashString)1282 {1283 long eltHash;1284 AutomationElement elt;1285 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1286 return -1;1287 var pattern = GetPattern(elt, ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;1288 if (pattern == null)1289 return -1;1290 var state = pattern.Current.ExpandCollapseState;1291 if (state == ExpandCollapseState.Expanded || state == ExpandCollapseState.PartiallyExpanded)1292 {1293 pattern.Collapse();1294 }1295 return 0;1296 }1297 public static int Expand(string eltHashString)1298 {1299 long eltHash;1300 AutomationElement elt;1301 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1302 return -1;1303 var pattern = GetPattern(elt, ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;1304 if (pattern == null)1305 return -1;1306 var state = pattern.Current.ExpandCollapseState;1307 if (state == ExpandCollapseState.Collapsed || state == ExpandCollapseState.PartiallyExpanded)1308 {1309 pattern.Expand();1310 }1311 return 0;1312 }1313 // ItemContainerPattern methods1314 public static int GetContainerItems(string eltHashString, string propertyName, string separator,1315 string filterSubChildClassName, string maxSubChildrenString, string scrollString)1316 {1317 long eltHash;1318 AutomationElement elt;1319 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1320 return -1;1321 AutomationProperty propertyField;1322 if (!stringToAutomationProperty.TryGetValue(propertyName, out propertyField))1323 {1324 return ReportFail(String.Format("Unknown property: \"{0}\"", propertyName));1325 }1326 var maxSubChildren = int.Parse(maxSubChildrenString);1327 var scroll = bool.Parse(scrollString.ToLower());1328 var pattern = GetPattern(elt, ItemContainerPattern.Pattern) as ItemContainerPattern;1329 if (pattern == null)1330 return -1;1331 var texts = new List<string>();1332 outStream.Write("[\0");1333 AutomationElement item = null;1334 while ((item = pattern.FindItemByProperty(item, null, null)) != null)1335 {1336 if (!ScrolledItem(item, scroll))1337 return -1;1338 CollectAllTexts(item, propertyField, filterSubChildClassName, maxSubChildren, texts, TreeWalker.RawViewWalker);1339 outStream.Write(String.Join(separator, texts) + '\0');1340 texts.Clear();1341 }1342 outStream.Write("]\0");1343 return 0;1344 }1345 // ScrollItemPattern methods1346 private static bool ScrolledItem(AutomationElement elt, bool scroll)1347 {1348 if (scroll)1349 {1350 var scrollPattern = GetPattern(elt, ScrollItemPattern.Pattern) as ScrollItemPattern;1351 if (scrollPattern == null)1352 {1353 return false;1354 }1355 else1356 {1357 scrollPattern.ScrollIntoView();1358 }1359 }1360 return true;1361 }1362 // SelectionPattern methods1363 public static int GetSelectedItems(string eltHashString, string propertyName, string separator,1364 string filterSubChildClassName, string maxSubChildrenString, string scrollString)1365 {1366 long eltHash;1367 AutomationElement elt;1368 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1369 return -1;1370 AutomationProperty propertyField;1371 if (!stringToAutomationProperty.TryGetValue(propertyName, out propertyField))1372 {1373 return ReportFail(String.Format("Unknown property: \"{0}\"", propertyName));1374 }1375 var maxSubChildren = int.Parse(maxSubChildrenString);1376 var scroll = bool.Parse(scrollString.ToLower());1377 var pattern = GetPattern(elt, SelectionPatternIdentifiers.Pattern) as SelectionPattern;1378 if (pattern == null)1379 return -1;1380 var current = pattern.Current;1381 var selection = current.GetSelection();1382 var texts = new List<string>();1383 outStream.Write("[\0");1384 foreach(AutomationElement item in selection)1385 {1386 if (!ScrolledItem(item, scroll))1387 return -1;1388 CollectAllTexts(item, propertyField, filterSubChildClassName, maxSubChildren, texts, TreeWalker.RawViewWalker);1389 outStream.Write(String.Join(separator, texts) + '\0');1390 texts.Clear();1391 }1392 outStream.Write("]\0");1393 return 0;1394 }1395 // TextPattern methods1396 public static int GetText(string eltHashString, string maxLengthString)1397 {1398 long eltHash;1399 AutomationElement elt;1400 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1401 return -1;1402 var pattern = GetPattern(elt, TextPattern.Pattern) as TextPattern;1403 if (pattern == null)1404 return -1;1405 var text = pattern.DocumentRange.GetText(int.Parse(maxLengthString));1406 outStream.Write("text=" + text + '\0');1407 return 0;1408 }1409 // ValuePattern methods1410 public static int SetValue(string eltHashString, string value)1411 {1412 long eltHash;1413 AutomationElement elt;1414 if (!GetElementFromHash(eltHashString, out eltHash, out elt))1415 return -1;1416 var pattern = GetPattern(elt, ValuePattern.Pattern) as ValuePattern;1417 if (pattern == null)1418 return -1;1419 pattern.SetValue(value);1420 return 0;1421 }1422 // Server methods1423 public static int SetCacheMode(string mode)1424 {1425 cacheMode = mode;1426 cacheElements = mode != "none";1427 return 0;1428 }1429 public static int ClearCache()1430 {1431 elements.Clear();1432 parents.Clear();1433 return 0;1434 }1435 public static void RunServer()1436 {1437 while (true)1438 {1439 var pipeServer = new NamedPipeServerStream("fmbtwindows_uiautomation", PipeDirection.InOut);1440 pipeServer.WaitForConnection();1441 outStream = new StreamWriter(pipeServer);1442 var sr = new StreamReader(pipeServer);1443 try1444 {1445 // Read parameters size and function name1446 var s = sr.ReadLine();1447 var index = s.IndexOf('\0');1448 var requestSize = int.Parse(s.Substring(0, index));1449 outStream.Write("#requestSize: " + requestSize + '\0');1450 var functionName = s.Substring(index + 1);1451 outStream.Write("#functionName: " + functionName + '\0');1452 // Read parameters in a single chunk of data1453 var charBuffer = new Char[requestSize];1454 var currLen = 0;1455 while (currLen < requestSize)1456 {1457 currLen += sr.Read(charBuffer, currLen, requestSize - currLen);1458 }1459 s = new String(charBuffer);1460 // Each parameter is separated by the special \0 character1461 var parameters = (s == "") ? null : s.Split('\0');1462 outStream.Write("#parameters:\0");1463 if (parameters != null)1464 {1465 foreach(var param in parameters)1466 {1467 outStream.Write('#' + param + '\0');1468 }1469 }1470 outStream.Write("#end-of-parameters\0");1471 var method = typeof(UI).GetMethod(functionName);1472 if (method == null)1473 {1474 ReportFail("Unknown function name: " + functionName);1475 }1476 else {1477 method.Invoke(null, parameters);1478 }1479 }1480 catch (Exception e)1481 {1482 ReportFail("Unhandled exception: " + e);1483 }1484 finally1485 {1486 outStream.Write("#end-of-dump");1487 outStream.Flush();1488 outStream.Close();1489 sr.Close();1490 }1491 pipeServer.Close();1492 }1493 }1494 }1495}1496'@1497Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $source -Language CSharp1498[FmbtWindows.UI]::RunServer()1499"""1500 fd, filename = tempfile.mkstemp(prefix="fmbtwindows-dumpwindow-", suffix=".ps1")1501 _g_rmAtExit.append(filename)1502 os.write(fd, powershellCode)1503 os.close(fd)1504 run_script = ["powershell.exe", "-ExecutionPolicy", "Unrestricted", filename]1505 server_process = subprocess.Popen(run_script)1506def _callServer(functionName, *args):1507 def toString(value):1508 if isinstance(value, (list, tuple)):1509 return ",".join(str(item) for item in value)1510 else:1511 return str(value)1512 serverLaunched = False1513 endTime = time.time() + 301514 while True:1515 try:1516 f = open(r"\\.\pipe\fmbtwindows_uiautomation", "r+")1517 break1518 except IOError:1519 if not serverLaunched:1520 launchUIAutomationServer()1521 serverLaunched = True1522 time.sleep(0.5)1523 if time.time() > endTime:1524 raise Exception("dump timed out: cannot connect to uiautomation server")1525 buf = "\0".join(toString(arg) for arg in args)1526 # \n counts as two characters on Windows!1527 request = "%s\0%s\n%s" % (len(buf) + buf.count('\n'), functionName, buf)1528 f.write(request)1529 f.flush()1530 rv = f.read()1531 f.close()1532 return rv1533def dumpUIAutomationElements(window=None, fromPath=[], properties=[], area=None, walker="raw",1534 filterType="none", filterCondition="", dumpChildClass="", dumpChildName="", doNotDump=False):...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful