Esempio n. 1
0
        /// <summary>
        /// Get DesktopElements based on Process Id.
        /// </summary>
        /// <param name="pid"></param>
        /// <returns>return null if we fail to get elements by process Id</returns>
        public static IEnumerable <DesktopElement> ElementsFromProcessId(int pid)
        {
            IUIAutomationElement         root         = null;
            IEnumerable <DesktopElement> elements     = null;
            IUIAutomationCondition       condition    = null;
            IUIAutomationElementArray    elementArray = null;

            try
            {
                // check whether process exists first.
                // if not, it will throw an ArgumentException
                using (var proc = Process.GetProcessById(pid))
                {
                    root         = UIAutomation.GetRootElement();
                    condition    = UIAutomation.CreatePropertyCondition(PropertyType.UIA_ProcessIdPropertyId, pid);
                    elementArray = root.FindAll(TreeScope.TreeScope_Children, condition);
                    elements     = ElementsFromUIAElements(elementArray);
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                // report and let it return null
                ex.ReportException();
            }
#pragma warning restore CA1031 // Do not catch general exception types
            finally
            {
                if (root != null)
                {
                    Marshal.ReleaseComObject(root);
                }
                if (condition != null)
                {
                    Marshal.ReleaseComObject(condition);
                }

                if (elementArray != null)
                {
                    Marshal.ReleaseComObject(elementArray);
                }
            }

            return(elements);
        }