Ejemplo n.º 1
0
        public bool TryFindWorkbookByName(out Excel.Workbook target)
        {
            var excelInstances = GetExcelInstances();

            if (excelInstances.Count == 0)
            {
                target = null;
                return(false);
            }

            foreach (var p in excelInstances)
            {
                var winHandle = p.MainWindowHandle;
                if (winHandle == IntPtr.Zero)
                {
                    continue;
                }

                if (!childWindowFinder.TryFindChildWindow(winHandle, out var hwndChild))
                {
                    continue;
                }

                if (!windowFinder.TryFindExcelWindow(hwndChild, out Excel.Window ptr))
                {
                    continue;
                }

                // If we successfully got a native OM
                // IDispatch pointer, we can QI this for
                // an Excel Application (using the implicit
                // cast operator supplied in the PIA).
                var workbooks = ptr.Application.Workbooks;
                if (TryFindWorkbook(workbooks, out var victim))
                {
                    target = victim;
                    return(true);
                }
            }

            target = null;
            return(false);
        }