Ejemplo n.º 1
4
        public string GetURL(int hwnd)
        {
            ShellWindows sw = new ShellWindows();
            
            IEnumerator windows = new ShellWindowsClass().GetEnumerator();
            while (windows.MoveNext())
            {
                if ((windows.Current as IWebBrowser2).HWND == hwnd)
                {
                    if ((windows.Current is IWebBrowser2))
                    {
                        IntPtr hw; 
                        IOleWindow win = ((windows.Current as IWebBrowser2).Document as IOleWindow);
                        if (win != null)
                        {
                            win.GetWindow(out hw);

                            if (IsWindowVisible(hw))
                            {
                                string activeTabUrl = ((windows.Current as IWebBrowser2).Document as mshtml.IHTMLDocument2).url;
                                return activeTabUrl;
                            }
                        }
                        else
                        {
                            return (windows.Current as IWebBrowser2).LocationURL;
                        }
                    }
                }
            }

            return "n/a";
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Opens the folder if not already open.
        /// </summary>
        /// <param name="folderLocation"></param>
        private static void OpenFolder(string folderLocation)
        {
            //don't open the folder if it's already open
            ShellWindows windows = new ShellWindows();

            List <string> openFolders = new List <string>();

            foreach (InternetExplorer ie in windows)
            {
                if (ie != null && ie.FullName != null && Path.GetFileNameWithoutExtension(ie.FullName).ToLower().Equals("explorer"))
                {
                    openFolders.Add(ie.LocationURL.ToLower().Trim(' ', '\t', '/'));
                }
            }

            string checkAgainst = "file:///" + folderLocation.ToLower().Trim(' ', '\t', '\\').Replace("\\", "/");

            if (folderLocation.StartsWith("\\\\"))
            {
                checkAgainst = "file://" + folderLocation.ToLower().Trim(' ', '\t', '\\').Replace("\\", "/");
            }

            if (!openFolders.Contains(checkAgainst))
            {
                Process.Start("explorer.exe", folderLocation);
            }
        }
Ejemplo n.º 3
0
        private void ProcessIExplore()
        {
            ShellWindows     ieShellWindows = new ShellWindows();
            string           sProcessType;
            InternetExplorer currentiexplore = null;

            foreach (InternetExplorer ieTab in ieShellWindows)
            {
                sProcessType = Path.GetFileNameWithoutExtension(ieTab.FullName).ToLower();
                if (sProcessType.Equals("iexplore") && !ieTab.LocationURL.Contains("about:Tabs"))
                {
                    currentiexplore = ieTab;
                }
            }

            if (currentiexplore != null)
            {
                if (currentiexplore.LocationURL.Equals(string.Empty))
                {
                    ProcessIExplore();
                }
                else
                {
                    Process.Start("chrome", currentiexplore.LocationURL);
                }
                currentiexplore.Quit();
                return;
            }
        }
    static void Main(string[] args)
    {
        var shellWindows = new ShellWindows();

        foreach (IWebBrowser2 win in shellWindows)
        {
            IServiceProvider sp = win as IServiceProvider;
            object           sb;
            sp.QueryService(SID_STopLevelBrowser, typeof(IShellBrowser).GUID, out sb);
            IShellBrowser shellBrowser = (IShellBrowser)sb;
            object        sv;
            shellBrowser.QueryActiveShellView(out sv);
            Console.WriteLine(win.LocationURL + " " + win.LocationName);
            IFolderView fv = sv as IFolderView;
            if (fv != null)
            {
                // only folder implementation support this (IE windows do not for example)
                object pf;
                fv.GetFolder(typeof(IPersistFolder2).GUID, out pf);
                IPersistFolder2 persistFolder = (IPersistFolder2)pf;
                // get folder class, for example
                // CLSID_ShellFSFolder for standard explorer folders
                Guid clsid;
                persistFolder.GetClassID(out clsid);
                Console.WriteLine(" clsid:" + clsid);
                // get current folder pidl
                IntPtr pidl;
                persistFolder.GetCurFolder(out pidl);
                // TODO: do something with pidl

                Marshal.FreeCoTaskMem(pidl);     // free pidl's allocated memory
            }
        }
    }
Ejemplo n.º 5
0
        internal void OpenLinkInNewTab(string url)
        {
            switch (type)
            {
            case BrowserType.IExplore:
            {
                bool         found = false;
                ShellWindows iExplorerInstances = new ShellWindows();
                foreach (InternetExplorer iExplorer in iExplorerInstances)
                {
                    if (iExplorer.Name == "Windows Internet Explorer")
                    {
                        iExplorer.Navigate(url, 0x800);
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    Process.Start(url);
                }
            }
            break;

            case BrowserType.Chrome:
            case BrowserType.Firefox:
            {
                var args = string.Format(GetNewTabOption(), url);
                StartBrowser(args);
            }
            break;
            }
        }
Ejemplo n.º 6
0
        public Form1()
        {
            InitializeComponent();
            WindowsInstance = new ShellWindows();

            Load += (s, e) => Close();
        }
Ejemplo n.º 7
0
        public void EnumerateWindows()
        {
            ListView1_initialize();

            listView1.BeginUpdate();

            Shell        shell = new Shell();
            ShellWindows win   = shell.Windows();

            foreach (IWebBrowser2 web in win)
            {
                try
                {
                    if (Path.GetFileName(web.FullName).ToUpper() == "EXPLORER.EXE")
                    {
                        string str = web.LocationURL;
                        if (str.Length == 0)
                        {
                            continue;
                        }                                  // LocationURL is empty for special folders (ex. Documents)

                        IntPtr hWnd = (IntPtr)web.HWND;

                        // Add
                        string[] newitem = { str, hWnd.ToString(), "" };
                        listView1.Items.Add(new ListViewItem(newitem));
                    }
                }
                catch (Exception ex)
                {
                    // Skip this window if something is wrong
                }
            }
            listView1.EndUpdate();
        }
Ejemplo n.º 8
0
        public static List <ExplorerPaths> GetExplorerFiles()
        {
            string windowName;
            List <ExplorerPaths> ret      = new List <ExplorerPaths>();
            ShellWindows         winClass = new ShellWindows();
            int cnt = 0;

            foreach (InternetExplorer window in winClass)
            {
                windowName = Path.GetFileNameWithoutExtension(window.FullName).ToLower();

                if (windowName.ToLowerInvariant() == "explorer")
                {
                    var           doc   = (IShellFolderViewDual2)window.Document;
                    ExplorerPaths expl  = new ExplorerPaths(cnt++, doc.Folder.Title);
                    FolderItems   items = doc.SelectedItems();

                    foreach (FolderItem item in items)
                    {
                        expl.Paths.Add(item.Path);
                    }

                    ret.Add(expl);
                }
            }

            return(ret);
        }
Ejemplo n.º 9
0
 public void Open(string[] urls)
 {
     if (urls.Length > 0)
     {
         foreach (var url in urls)
         {
             ShellWindows iExplorerInstances = new ShellWindows();
             bool         found = false;
             foreach (InternetExplorer iExplorer in iExplorerInstances)
             {
                 if (iExplorer.Name == "Internet Explorer")
                 {
                     iExplorer.Navigate(url, 0x800);
                     found = true;
                     break;
                 }
             }
             if (!found)
             {
                 Console.WriteLine("Created New Instance, because not found!");
                 var proc = Process.Start("IExplore.exe", url);
                 proc.WaitForInputIdle();
                 Thread.Sleep(2000);
             }
         }
     }
 }
Ejemplo n.º 10
0
        public bool SwitchToWindow(string url)
        {
            var shellWindows = new ShellWindows();

            foreach (SHDocVw.WebBrowser webBrowser in shellWindows)
            {
                var nameWindow = webBrowser?.Name;
                if (nameWindow == null)
                {
                    continue;
                }

                if (nameWindow.Contains("Internet"))
                {
                    var urlWindow = webBrowser?.LocationURL;
                    if (urlWindow == null)
                    {
                        continue;
                    }

                    if (urlWindow.Equals(url))
                    {
                        Navegador = (InternetExplorer)webBrowser;
                        return(true);
                    }
                }
            }

            return(false);
        }
        public override List <Control> Render(frmCommandEditor editor)
        {
            base.Render(editor);

            RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor));

            IEBrowerNameDropdown = (ComboBox)CommandControls.CreateDropdownFor("v_IEBrowserName", this);
            var shellWindows = new ShellWindows();

            foreach (IWebBrowser2 shellWindow in shellWindows)
            {
                if (shellWindow.Document is MSHTML.HTMLDocument)
                {
                    IEBrowerNameDropdown.Items.Add(shellWindow.Document.Title);
                }
            }
            RenderedControls.Add(CommandControls.CreateDefaultLabelFor("v_IEBrowserName", this));
            RenderedControls.AddRange(CommandControls.CreateUIHelpersFor("v_IEBrowserName", this, new Control[] { IEBrowerNameDropdown }, editor));
            //IEBrowerNameDropdown.SelectionChangeCommitted += seleniumAction_SelectionChangeCommitted;
            RenderedControls.Add(IEBrowerNameDropdown);

            //ElementParameterControls = new List<Control>();
            //ElementParameterControls.Add(CommandControls.CreateDefaultLabelFor("v_WebActionParameterTable", this));
            //ElementParameterControls.AddRange(CommandControls.CreateUIHelpersFor("v_WebActionParameterTable", this, new Control[] { ElementsGridViewHelper }, editor));
            //ElementParameterControls.Add(ElementsGridViewHelper);

            //RenderedControls.AddRange(ElementParameterControls);

            return(RenderedControls);
        }
Ejemplo n.º 12
0
        public static void WriteExcel1(string ExcelName, string Province, string WenLi, string Year, string MajorName, string Score, string School, string PiCi)
        {
            ShellWindows windows = new ShellWindows();

            Microsoft.Office.Interop.Excel.Workbook wb = null;

            Microsoft.Office.Interop.Excel.Application ExcelApp = (Microsoft.Office.Interop.Excel.Application)Marshal.GetActiveObject("Excel.Application");
            foreach (Microsoft.Office.Interop.Excel.Workbook item in ExcelApp.Workbooks)
            {
                if (item.Name.Contains(ExcelName))
                {
                    wb = item;
                    break;
                }
            }

            Microsoft.Office.Interop.Excel.Range Rng = wb.Sheets[1].Range("F100000").End[Microsoft.Office.Interop.Excel.XlDirection.xlUp].Offset[1, 0];

            Rng.Value = MajorName;
            Rng.Offset[0, -5].Value = Province;
            Rng.Offset[0, -4].Value = Year;
            Rng.Offset[0, -3].Value = School;
            Rng.Offset[0, -2].Value = WenLi;
            Rng.Offset[0, -1].Value = PiCi;
            Rng.Offset[0, 1].Value  = Score;
        }
Ejemplo n.º 13
0
        public override ActionResult Execute(ISpecialExecutionTaskTestAction testAction)
        {
            bool        completed     = false;
            string      returnMsg     = "";
            IInputValue paramURL      = testAction.GetParameterAsInputValue(URL, false);
            IInputValue paramIsNewTab = testAction.GetParameterAsInputValue(isNewTab, false);

            if (paramURL == null || string.IsNullOrEmpty(paramURL.Value))
            {
                throw new ArgumentException(string.Format("Mandatory parameter '{0}' not set.", URL));
            }

            if (paramIsNewTab == null || string.IsNullOrEmpty(paramIsNewTab.Value))
            {
                throw new ArgumentException(string.Format("Mandatory parameter '{0}' not set.", isNewTab));
            }

            try
            {
                if (paramIsNewTab.Value == "True")
                {
                    ShellWindows shellWindows = new ShellWindows();  //Uses SHDocVw to get the Internet Explorer Instances
                    foreach (SHDocVw.InternetExplorer internetExplorerInstance in shellWindows)
                    {
                        string url = internetExplorerInstance.LocationURL;
                        if (!url.Contains("file:///"))
                        {
                            internetExplorerInstance.Navigate(paramURL.Value, 0x800);
                            completed = true;
                            returnMsg = "URL opened in new tab";
                            break;
                        }
                    }
                }

                if (!completed)   // To open url in new window
                {
                    Process procInNewWndow = new Process();
                    procInNewWndow.StartInfo.FileName        = "C:\\Program Files\\Internet Explorer\\iexplore.exe";
                    procInNewWndow.StartInfo.Arguments       = paramURL.Value;
                    procInNewWndow.StartInfo.UseShellExecute = true;
                    procInNewWndow.StartInfo.CreateNoWindow  = false;
                    procInNewWndow.Start();
                    returnMsg = "URL opened in new window";
                }
            }
            catch (Exception)
            {
                return(new UnknownFailedActionResult("Could not start program",
                                                     string.Format(
                                                         "Failed while trying to start:\nURL: {0}\r\nIsNewTab: {1}",
                                                         paramURL.Value, paramIsNewTab.Value),
                                                     ""));
            }

            return(new PassedActionResult(returnMsg));
        }
Ejemplo n.º 14
0
        public ExplorerBrowserService()
        {
            this.historyQueue = new Queue <ExplorerHistory>();

            this.shellWindows = new ShellWindows();
            this.shellWindows.WindowRegistered += this.shellWindowsOnWindowRegistered;

            this.registerEvent(true);
        }
		private void UpdateExplorerWindows()
		{
			if (_explorerWindows != null)
				return;

			var shellWindows = new ShellWindows();

			_explorerWindows = shellWindows.Cast<InternetExplorer>().ToArray();
		}
Ejemplo n.º 16
0
        private void UpdateExplorerWindows()
        {
            if (_explorerWindows != null)
            {
                return;
            }

            var shellWindows = new ShellWindows();

            _explorerWindows = shellWindows.Cast <InternetExplorer>().ToArray();
        }
Ejemplo n.º 17
0
        void Test()
        {
            ShellWindows shellWindows = new ShellWindows();

            try
            {
                foreach (IWebBrowser2 win in shellWindows)
                {
                    WinAPI.IServiceProvider sp = win as WinAPI.IServiceProvider;
                    object sb;
                    sp.QueryService(SID_STopLevelBrowser, typeof(IShellBrowser).GUID, out sb);


                    IShellBrowser shellBrowser = (IShellBrowser)sb;
                    IShellView    sv;
                    shellBrowser.QueryActiveShellView(out sv);
                    Console.WriteLine(win.LocationURL + " " + win.LocationName);
                    IFolderView fv = sv as IFolderView;

                    if (fv != null)
                    {
                        Timer t = new Timer();
                        t.Interval = 200;
                        t.Tick    += (o, se) => {
                            int fitem;
                            if (0 == fv.GetFocusedItem(out fitem))
                            {
                                IntPtr pid;
                                if (0 == fv.Item(fitem, out pid))
                                {
                                    //invokea(pid);
                                }

                                Marshal.FreeHGlobal(pid);
                            }
                        };
                        t.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (shellWindows != null)
                {
                    Marshal.ReleaseComObject(shellWindows);
                }
            }
        }
Ejemplo n.º 18
0
        private InternetExplorer LauchBrowser()
        {
            string IELocation = @"C:\Program Files\Internet Explorer\iexplore.exe";

            IELocation = System.Environment.ExpandEnvironmentVariables(IELocation);

            //Console.WriteLine("Launching IE ");
            Process p = Process.Start(IELocation, "about:blank");

            //int handle = (int)p.MainWindowHandle;
            Thread.Sleep(3000);

            //Console.WriteLine("Attaching to IE ... ");
            InternetExplorer ie = null;

            try
            {
                //if (p != null)
                //{
                //Console.WriteLine("Process handle is: " + p.MainWindowHandle.ToString());
                SHDocVw.ShellWindows allBrowsers = new ShellWindows();
                //Console.WriteLine("Number of active IEs :" + allBrowsers.Count.ToString());
                if (allBrowsers.Count != 0)
                {
                    for (int i = 0; i < allBrowsers.Count; i++)
                    {
                        InternetExplorer e = (InternetExplorer)allBrowsers.Item(i);
                        if (e != null)
                        {
                            if (e.LocationURL == "about:blank")
                            //if (e.HWND == (int)p.MainWindowHandle)
                            {
                                ie = e;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("Faul to find IE");
                }
                //}
                //else
                //    throw new Exception("Fail to launch IE");
            }
            catch (Exception e)
            {
                throw e;
            }
            return(ie);
        }
Ejemplo n.º 19
0
Archivo: Form1.cs Proyecto: Kgrah/Saver
        public static void iEInstances()
        {
            ShellWindows iEInstances = new ShellWindows();

            string[] arr = new string[1000];
            int      i   = 0;

            foreach (InternetExplorer ie in iEInstances)
            {
                arr[i++] = ie.Name;
                MessageBox.Show(ie.LocationName);
            }
        }
        internal static void enableToolbar()
        {
            ShellWindows shellWindows = new ShellWindows();

            foreach (InternetExplorer ie in shellWindows)
            {
                String filename = ie.Name;
                if (filename.Contains("Internet Explorer"))
                {
                    ie.ToolBar = 1;
                }
            }
        }
Ejemplo n.º 21
0
        public static void open_url(Browser b, bool incognito = false)
        {
            var args = new List <string>();

            if (!string.IsNullOrEmpty(b.additionalArgs))
            {
                args.Add(b.additionalArgs);
            }
            if (incognito)
            {
                args.Add(b.private_arg);
            }
            if (b.exec.ToLower().EndsWith("brave.exe"))
            {
                args.Add("--");
            }
            args.Add(Program.url.Replace("\"", "%22"));

            if (b.exec.EndsWith("iexplore.exe") && !incognito)
            {
                // IE tends to open in a new window instead of a new tab
                // code borrowed from http://stackoverflow.com/a/3713470/1461004
                bool         found = false;
                ShellWindows iExplorerInstances = new ShellWindows();
                foreach (InternetExplorer iExplorer in iExplorerInstances)
                {
                    if (iExplorer.Name.EndsWith("Internet Explorer"))
                    {
                        iExplorer.Navigate(Program.url, 0x800);
                        // for issue #10 (bring IE to focus after opening link)
                        ForegroundAgent.RestoreWindow(iExplorer.HWND);
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    Process.Start(b.exec, Program.Args2Str(args));
                }
            }
            else
            {
                ProcessStartInfo startInfo = new ProcessStartInfo(b.exec);
                // Clicking MS Edge takes more than 4 seconds to load, even with an existing window
                // Disabling UseShellExecute to create the process directly from the browser executable file
                startInfo.UseShellExecute = false;
                startInfo.Arguments       = Program.Args2Str(args);
                Process.Start(startInfo);
            }
            Application.Exit();
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Run/evaluate JavaScript code in the DOM context.
 /// </summary>
 /// <param name="browserWindow">The browser window.</param>
 /// <param name="code">The JavaScript code</param>
 public static void RunScript(BrowserWindow browserWindow, string code)
 {
     SHDocVw.InternetExplorer internetExplorer = null;
     ShellWindows shellWindows = new ShellWindows();
     foreach (SHDocVw.InternetExplorer shellWindow in shellWindows)
     {
         if (shellWindow.HWND == browserWindow.WindowHandle.ToInt32())
         {
             internetExplorer = shellWindow;
             break;
         }
     }
     internetExplorer.Document.parentWindow.execScript(code);
 }
Ejemplo n.º 23
0
        public static void Kill()
        {
            var shellWindows = new ShellWindows();

            foreach (InternetExplorer ie in shellWindows)
            {
                // This parses the name of the process
                var processType = Path.GetFileNameWithoutExtension(ie.FullName)?.ToLower();
                if (processType != null && processType.Equals("explorer"))
                {
                    ie.Quit();
                }
            }
        }
        private void fetchExplorerInfo()
        {
            var windows = new ShellWindows();
            var foreground = User32.GetForegroundWindow();
            foreach (InternetExplorer item in windows)
            {
                if (item.HWND != foreground.ToInt32()) continue;

                var workingDir = new Uri(item.LocationURL).LocalPath;
                if (Directory.Exists(workingDir)) CorePlugin.WorkingDirectory.Set(workingDir);
                var workingFile = item.Document.FocusedItem.Path;
                if (File.Exists(workingDir)) CorePlugin.WorkingFile.Set(workingDir);
            }
        }
        private void Execute()
        {
            while (true)
            {
                var shellWindows = new ShellWindows();
                foreach (var ieInst in from InternetExplorer ieInst in shellWindows let url = ieInst.LocationURL where url.Contains("Ombuds") select ieInst)
                {
                    ieInst.Quit();
                }

                // Sleep for 10 sec
                Thread.Sleep(10000);
            }
        }
Ejemplo n.º 26
0
        public void ShellTest()
        {
            var shellWindows = new ShellWindows();

            foreach (IWebBrowser2 win in shellWindows)
            {
                IServiceProvider sp = win as IServiceProvider;
                object           sb;
                sp.QueryService(SID_STopLevelBrowser, typeof(IShellBrowser).GUID, out sb);
                IShellBrowser shellBrowser = (IShellBrowser)sb;
                object        sv;
                shellBrowser.QueryActiveShellView(out sv);
                Console.WriteLine(win.LocationURL + " " + win.LocationName);
                IFolderView fv = sv as IFolderView;
                if (fv != null)
                {
                    // only folder implementation support this (IE windows do not for example)
                    object pf;
                    fv.GetFolder(typeof(IPersistFolder2).GUID, out pf);
                    IPersistFolder2 persistFolder = (IPersistFolder2)pf;
                    // get folder class, for example
                    // CLSID_ShellFSFolder for standard explorer folders
                    Guid clsid;
                    persistFolder.GetClassID(out clsid);
                    Console.WriteLine(" clsid:" + clsid);
                    int   pitem;
                    Timer timer = new Timer(new TimerCallback(stat =>
                    {
                        //if (0 == fv.GetFocusedItem(out pitem))
                        //{
                        //    Console.WriteLine(pitem);
                        //}
                        if (0 == fv.ItemCount(0x00000001, out pitem))
                        {
                            Console.WriteLine(pitem);
                        }
                    }));
                    timer.Change(200, 0);

                    // get current folder pidl
                    IntPtr pidl;
                    persistFolder.GetCurFolder(out pidl);

                    // TODO: do something with pidl

                    Marshal.FreeCoTaskMem(pidl); // free pidl's allocated memory
                }
            }
        }
Ejemplo n.º 27
0
        public List <InternetExplorer> GetIeInstances()
        {
            _ieWindows.Clear();
            ShellWindows shellWindows = new ShellWindows();

            foreach (InternetExplorer ie in shellWindows)
            {
                string filename = Path.GetFileNameWithoutExtension(ie.FullName)?.ToLower();
                if (filename != null && filename.Equals("iexplore"))
                {
                    _ieWindows.Add(ie);
                }
            }
            return(_ieWindows);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Create a new instance of IExplorer with Process.start()
        /// Store the handle of the new process
        /// </summary>
        public WebUtil()
        {
            m_IEFoundBrowsers = new ShellWindows();  //all shells
            int explorerInstances = m_IEFoundBrowsers.Count;

            //open a new instance of IExplore, the nomerge attribute is for generate a new HWND for the new instance,
            //other way the new instance will be hooked by the last instance
            m_proc = Process.Start("IExplore.exe", "-nomerge about:blank");
            while (explorerInstances == m_IEFoundBrowsers.Count)
            {
                ///keep program busy till the windows shell get the new instance
            }
            SetIEHandle();
            AtachEventHls();
        }
Ejemplo n.º 29
0
        private void DebugLog()
        {
            if (this._logger == null)
            {
                return;
            }

            // Print out found Shell Windows and their info.
            var shellWindows = new ShellWindows();

            foreach (IWebBrowser2 wnd in shellWindows)
            {
                this._logger.Log(LogLevel.Debug, $"Found Shell Window: {wnd.Name} (Name)\n\tLocationName: {wnd.LocationName}\n\tFullName: {wnd.FullName}");
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Run/evaluate JavaScript code in the DOM context.
        /// </summary>
        /// <param name="browserWindow">The browser window.</param>
        /// <param name="code">The JavaScript code</param>
        public static void RunScript(BrowserWindow browserWindow, string code)
        {
            SHDocVw.InternetExplorer internetExplorer = null;
            ShellWindows             shellWindows     = new ShellWindows();

            foreach (SHDocVw.InternetExplorer shellWindow in shellWindows)
            {
                if (shellWindow.HWND == browserWindow.WindowHandle.ToInt32())
                {
                    internetExplorer = shellWindow;
                    break;
                }
            }
            internetExplorer.Document.parentWindow.execScript(code);
        }
Ejemplo n.º 31
0
        //-------------------------------------------------------------------------------------------------------------
        public void OpenUrl(BrowserModel browser, bool incognito = false)
        //-------------------------------------------------------------------------------------------------------------
        {
            var args = new List <string>();

            if (!string.IsNullOrEmpty(browser.additionalArgs))
            {
                args.Add(browser.additionalArgs);
            }
            if (incognito)
            {
                args.Add(browser.privateArg);
            }
            if (browser.exec.ToLower().EndsWith("brave.exe"))
            {
                args.Add("--");
            }
            args.Add(BrowserSelectApp.url.Replace("\"", "%22"));

            if (browser.exec.EndsWith("iexplore.exe") && !incognito)
            {
                // IE tends to open in a new window instead of a new tab
                // code borrowed from http://stackoverflow.com/a/3713470/1461004
                bool         found = false;
                ShellWindows iExplorerInstances = new ShellWindows();
                foreach (InternetExplorer iExplorer in iExplorerInstances)
                {
                    if (iExplorer.Name.EndsWith("Internet Explorer"))
                    {
                        iExplorer.Navigate(BrowserSelectApp.url, 0x800);
                        // for issue #10 (bring IE to focus after opening link)
                        ForegroundAgent.RestoreWindow(iExplorer.HWND);
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    Process.Start(browser.exec, args2Str(args));
                }
            }
            else
            {
                Process.Start(browser.exec, args2Str(args));
            }

            Application.Exit();
        }
Ejemplo n.º 32
0
        internal ExplorerCleaner(ExplorerWindowCleanerAppConfig appConfig)
        {
            _appConfig           = appConfig;
            _explorerDic         = new Dictionary <int, Explorer>();
            _closedExplorerDic   = new ConcurrentDictionary <string, Explorer>();
            _restoreExplorerDic  = new Dictionary <int, Explorer>();
            _pinedRestoreHashSet = new HashSet <string>();
            Explorers            = new ObservableCollection <Explorer>();
            ClosedExplorers      = new ObservableCollection <Explorer>();
            BindingOperations.EnableCollectionSynchronization(Explorers, new object());
            BindingOperations.EnableCollectionSynchronization(ClosedExplorers, new object());
            _shellWindows = new ShellWindowsClass();

            _specialFolderManager = new SpecialFolderManager();
            Restore();
        }
Ejemplo n.º 33
0
        public static string GetActiveExplorerPath()
        {
            // get the active window
            IntPtr handle = GetExplorerPointer();

            // Required ref: SHDocVw (Microsoft Internet Controls COM Object) - C:\Windows\system32\ShDocVw.dll
            var shellWindows = new ShellWindows();

            // loop through all windows
            foreach (InternetExplorer window in shellWindows)
            {
                // match active window
                if (window.HWND == (int)handle)
                {
                    // Required ref: Shell32 - C:\Windows\system32\Shell32.dll
                    var shellWindow = window.Document as Shell32.IShellFolderViewDual2;

                    // will be null if you are in Internet Explorer for example
                    if (shellWindow != null)
                    {
                        // Item without an index returns the current object
                        var currentFolder = shellWindow.Folder.Items().Item();

                        // special folder - use window title
                        // for some reason on "Desktop" gives null
                        if (currentFolder == null || currentFolder.Path.StartsWith("::"))
                        {
                            // Get window title instead
                            const int     nChars = 256;
                            StringBuilder Buff   = new StringBuilder(nChars);
                            if (_GetWindowText(handle, Buff, nChars) > 0)
                            {
                                return(Buff.ToString());
                            }
                        }
                        else
                        {
                            return(currentFolder.Path);
                        }
                    }

                    break;
                }
            }

            return(null);
        }
Ejemplo n.º 34
0
        public bool Perform(KeybindDevice device, Keys key, KeyState state, KeyState lastState, string guid, params object[] args)
        {
            if (args.Length < 1 || !(args[0] is string path) || string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
            {
                return(false);
            }

            path = path.Replace("/", "\\").TrimEnd('\\');

            IntPtr hwnd = IntPtr.Zero;

            ShellWindows shellWindows = new ShellWindows();

            foreach (InternetExplorer ie in shellWindows)
            {
                if (!Path.GetFileNameWithoutExtension(ie.FullName).ToLower().Equals("explorer"))
                {
                    continue;
                }

                try
                {
                    string folderpath = new Uri(ie.LocationURL).LocalPath;

                    if (folderpath == path)
                    {
                        hwnd = (IntPtr)ie.HWND;

                        break;
                    }
                }
                catch
                {
                }
            }

            if (hwnd == IntPtr.Zero)
            {
                Process.Start(path);
            }
            else
            {
                RestoreWindow(hwnd);
            }

            return(true);
        }
 public ExplorerManager(string startPath)
 {
     if (!string.IsNullOrEmpty(startPath))
     {
         _workingDirectory = Path.GetDirectoryName(startPath);
         var shellWindows = new ShellWindows();
         foreach (InternetExplorer window in shellWindows)
         {
             string explorerLocationPath = new Uri(window.LocationURL).LocalPath;
             if (_workingDirectory.Equals(explorerLocationPath, StringComparison.InvariantCultureIgnoreCase))
             {
                 _explorerWindow = window;
                 break;
             }
         }
     }
 }
Ejemplo n.º 36
0
        private bool onShowExplorePath(string path)
        {
            bool         isFind = false;
            ShellWindows wins   = new ShellWindows();

            foreach (InternetExplorer w in wins)
            {
                if (w.LocationURL.Contains(path.Replace('\\', '/')))
                {
                    // 找到了窗口就置顶
                    Win32API.SetForegroundWindow((IntPtr)w.HWND);
                    isFind = true;
                    break;
                }
            }
            return(isFind);
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Performs an operation on each instance of Internet Explorer
 /// </summary>
 /// <param name="operation"></param>
 public static void TryForEachInternetExplorer(IEOperation operation, bool justOnce = false)
 {
     ShellWindows iExplorerInstances = new ShellWindows();
     foreach (var iExplorerInstance in iExplorerInstances)
     {
         try
         {
             var iExplorer = (InternetExplorer)iExplorerInstance;
             if (iExplorer.Name == "Internet Explorer" || iExplorer.Name == "Windows Internet Explorer")
             {
                 operation(iExplorer);
                 if (justOnce)
                     break;
             }
         }
         catch (Exception) { }
     }
 }
Ejemplo n.º 38
0
        public override object Suspend( SuspendInformation toSuspend )
        {
            var cabinetWindows = new ShellWindows()
                .Cast<InternetExplorer>()
                // TODO: Is there a safer way to guarantee that it is actually the explorer we expect it to be?
                // For some reason, the process CAN be both "Explorer", and "explorer".
                .Where( e => Path.GetFileNameWithoutExtension( e.FullName ).IfNotNull( p => p.ToLower() ) == "explorer" )
                .ToList();

            var suspendedExplorerWindows = new List<ExplorerLocation>();
            foreach ( Window window in toSuspend.Windows )
            {
                // Check whether the window is an explorer cabinet window. (file browser)
                InternetExplorer cabinetWindow = cabinetWindows.FirstOrDefault( e =>
                {
                    try
                    {
                        return window.Handle.Equals( new IntPtr( e.HWND ) );
                    }
                    catch ( COMException )
                    {
                        // This exception is thrown when accessing 'HWND' for some windows.
                        // TODO: Why is this the case, and do we ever need to handle those windows?
                        return false;
                    }
                } );
                if ( cabinetWindow != null )
                {
                    var persistedData = new ExplorerLocation
                    {
                        LocationName = cabinetWindow.LocationName,
                        LocationUrl = cabinetWindow.LocationURL,
                        Pidl = cabinetWindow.GetPidl()
                    };
                    cabinetWindow.Quit();
                    suspendedExplorerWindows.Add( persistedData );
                }

                // TODO: Support other explorer windows, e.g. property windows ...
            }

            return suspendedExplorerWindows;
        }
Ejemplo n.º 39
0
		public IECollection(bool waitForComplete)
		{
			_waitForComplete = waitForComplete;

			internetExplorers = new ArrayList();

			ShellWindows allBrowsers = new ShellWindows();

			foreach (SHDocVw.InternetExplorer internetExplorer in allBrowsers)
			{
				try
				{
					if (internetExplorer.Document is IHTMLDocument2)
					{
						IE ie = new IE(internetExplorer);
						internetExplorers.Add(ie);
					}
				}
				catch {}
			}
		}
Ejemplo n.º 40
0
        public SmartIE GetExistingInternetExplorerByHwnd(IntPtr hwnd)
        {
            var allBrowsers = new ShellWindows();

            foreach (InternetExplorer internetExplorer in allBrowsers)
            {
                try
                {
                    if (internetExplorer.Document is IHTMLDocument2)
                    {
                        if (new IntPtr( internetExplorer.HWND) == hwnd)
                        {
                            return new SmartIE(internetExplorer);
                        }
                    }
                }
                catch
                {
                }
            }
            return null;
        }
Ejemplo n.º 41
0
        /* InternetExplorer[] GetAllBrowsers()
         * get all the browsers currently.
         */
        protected virtual InternetExplorer[] GetAllBrowsers()
        {
            //get all shell browser.
            SHDocVw.ShellWindows allBrowsers = new ShellWindows();
            if (allBrowsers.Count > 0)
            {
                List<InternetExplorer> ieList = new List<InternetExplorer>(allBrowsers.Count);
                for (int i = allBrowsers.Count - 1; i >= 0; i--)
                {
                    try
                    {
                        InternetExplorer curIE = (InternetExplorer)allBrowsers.Item(i);
                        if (curIE != null && curIE.Document is IHTMLDocument)
                        {
                            ieList.Add(curIE);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                return ieList.ToArray();
            }

            return null;
        }
Ejemplo n.º 42
0
        protected virtual InternetExplorer WaitForBrowserExist(string title, string url, bool isReg)
        {
            Regex titleReg = null;
            Regex urlReg = null;
            if (isReg)
            {
                if (!String.IsNullOrEmpty(title))
                {
                    titleReg = new Regex(title, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }
                if (!String.IsNullOrEmpty(url))
                {
                    urlReg = new Regex(url, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }
            }

            int times = 0;
            while (times <= AppTimeout)
            {
                bool browserFound = false;

                //get all shell browser.
                SHDocVw.ShellWindows allBrowsers = new ShellWindows();
                if (allBrowsers.Count > 0)
                {
                    for (int i = allBrowsers.Count - 1; i >= 0; i--)
                    {
                        try
                        {
                            InternetExplorer curIE = (InternetExplorer)allBrowsers.Item(i);
                            if (curIE != null && curIE.Document is IHTMLDocument)
                            {
                                if (curIE.HWND != 0)
                                {
                                    //if all null, use any one.
                                    browserFound = _appProcess == null && String.IsNullOrEmpty(title) && String.IsNullOrEmpty(url);

                                    if (_appProcess != null && GetBrowserMajorVersion() < 8)
                                    {
                                        int pid = _appProcess.Id;
                                        browserFound = pid == Win32API.GetWindowThreadProcessId((IntPtr)curIE.HWND);
                                    }
                                    else
                                    {
                                        //by title
                                        if (!String.IsNullOrEmpty(title))
                                        {
                                            try
                                            {
                                                if (isReg)
                                                {
                                                    browserFound = titleReg != null && titleReg.IsMatch(curIE.LocationName);
                                                }
                                                else
                                                {
                                                    browserFound = (curIE.LocationName + TestConstants.IE_Title_Tail).IndexOf(title, StringComparison.CurrentCultureIgnoreCase) >= 0;
                                                }
                                            }
                                            catch
                                            {
                                                continue;
                                            }
                                        }

                                        //by URL
                                        if (!String.IsNullOrEmpty(url))
                                        {
                                            try
                                            {
                                                if (isReg)
                                                {
                                                    browserFound = urlReg != null && urlReg.IsMatch(curIE.LocationURL);
                                                }
                                                else
                                                {
                                                    browserFound = curIE.LocationURL.EndsWith(url, StringComparison.CurrentCultureIgnoreCase);
                                                }
                                            }
                                            catch
                                            {
                                                continue;
                                            }
                                        }
                                    }

                                    if (browserFound)
                                    {
                                        int pid = 0;
                                        Win32API.GetWindowThreadProcessId((IntPtr)curIE.HWND, out pid);
                                        _appProcess = System.Diagnostics.Process.GetProcessById(pid);

                                        return curIE;
                                    }
                                }
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }

                //IE8 is mutli process model, we may can not find it by process we started.
                if (String.IsNullOrEmpty(url))
                {
                    if (GetBrowserMajorVersion() > 7)
                    {
                        url = TestConstants.IE_BlankPage_Url;
                        _appProcess = null;
                    }
                }

                //sleep for 3 seconds, find again.
                times += Interval;
                Thread.Sleep(Interval * 1000);
            }

            return null;
        }
Ejemplo n.º 43
0
        private static mshtml.IHTMLDocument2 FindFirstPPTFrame(
            out double frameLeft,
            out double frameTop)
        {
            ShellWindows windows = new ShellWindows();
            foreach (InternetExplorer explorer in windows)
            {
                IntPtr handle = (IntPtr)explorer.HWND;
                mshtml.IHTMLDocument2 doc;

                try
                {
                    doc = explorer.Document;
                }
                catch (InvalidCastException)
                {
                    continue;
                }

                if (doc.frames != null)
                {
                    for (int i = 0; i < doc.frames.length; i++)
                    {
                        mshtml.IHTMLWindow2 frameWindow = doc.frames.item(i);

                        mshtml.IHTMLDocument2 frameDoc = null;
                        try
                        {
                            frameDoc = frameWindow.document;
                        }
                        catch(System.UnauthorizedAccessException)
                        { }

                        // convert IHTMLWindow2 to IWebBrowser2 using IServiceProvider.
                        IServiceProvider sp = (IServiceProvider)frameWindow;

                        // Use IServiceProvider.QueryService to get IWebBrowser2 object
                        object brws = null;
                        sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out brws);

                        // Get the document from IWebBrowser2
                        //SHDocVw.IWebBrowser2 browser = (SHDocVw.IWebBrowser2)brws;
                        InternetExplorer browser = (InternetExplorer)brws;
                        frameDoc = (mshtml.IHTMLDocument2)browser.Document;

                        if (frameDoc != null && frameDoc.url.Contains(WacPPTURLPattern))
                        {
                            // get the screen position of frame
                            AutomationElement autoEle = AutomationElement.FromHandle(handle);
                            var ieServerEle = autoEle.FindFirst(
                                TreeScope.Element | TreeScope.Descendants,
                                new PropertyCondition(
                                    AutomationElement.ClassNameProperty,
                                    "Internet Explorer_Server"));

                            if (ieServerEle != null)
                            {
                                SwitchToThisWindow(handle, true);
                                frameLeft = ieServerEle.Current.BoundingRectangle.Left;
                                frameTop = ieServerEle.Current.BoundingRectangle.Top;
                                return frameDoc;
                            }
                        }
                    }
                }
            }

            frameLeft = 0;
            frameTop = 0;
            return null;
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Internet Explorer Openner
        /// </summary>
        /// <author> KZ</author> 
        /// <date> 2015.08.17  </date>
        public void InternetExplorerOpenner(string Url)
        {
            ShellWindows iExplorerInstances = new ShellWindows();
            InternetExplorer currentiExplorer=null;
            bool found = false;
            Uri myUri = new Uri(Url);
            string host = myUri.Host;

            foreach (InternetExplorer iExplorer in iExplorerInstances)
            {

             //search opened IE
             if(iExplorer.Name.Contains("Internet Explorer"))
                {
                    currentiExplorer = iExplorer;

                    //search opened IE by URL
                    if (iExplorer.LocationURL.Contains(host))
                    {

                        var hWnd = (IntPtr)iExplorer.HWND;
                        new TabActivator(hWnd).ActivateByTabsUrl(Url);
                        ShowWindow(hWnd, (int)SW.SHOWMAXIMIZED);
                        SetForegroundWindow(hWnd);
                        found = true;
                        break;
                    }
                }
            }

            //Open URL if the IE has opened and the URL hasn't opened
            if (currentiExplorer != null && !found)
            {
                var hWnd = (IntPtr)currentiExplorer.HWND;
                currentiExplorer.Navigate(Url, 0x800);
                ShowWindow(hWnd, (int)SW.SHOWMAXIMIZED);
                SetForegroundWindow(hWnd);
                found = true;
            }

            //Open URL if the IE hasn't opened
            if (!found)
            {
                Process.Start("IEXPLORE.EXE", Url);
            }
        }
        /// <summary>
        /// Intializes ieHandler to be able to work with
        /// HTML objects.
        /// </summary>
        private void InitializeHandler()
        {
            // Iterate through open explorer windows to find the one that
            // matches the base process ID.
            //
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            while (this.ie == null && stopwatch.ElapsedMilliseconds < ScriptProperties.Timeout)
            {
                ShellWindows sh = new ShellWindows();

                foreach (InternetExplorer browser in sh)
                {
                    if (browser.Name.StartsWith("Internet"))
                    {
                        // Check the browser's HWND vs. that of the started application
                        // to ensure uniqueness, if the window was started through Ice.
                        //
                        if (this.isURL)
                        {
                            if (browser.HWND == base.GetHWND())
                            {
                                this.ie = browser;
                                break;
                            }
                        }
                        // If not started through Ice, check the tab's name vs. the
                        // window identifier.
                        //
                        else
                        {
                            if (browser.LocationName.Equals(this.windowIdentifier))
                            {
                                this.ie = browser;
                                break;
                            }
                        }
                    }
                    // Release current iteration of sh
                    //
                    Marshal.ReleaseComObject(browser);
                }

                // Release sh
                //
                Marshal.ReleaseComObject(sh);
            }

            // Check if browser was found
            //
            if (this.ie == null)
            {
                throw new WindowNotFoundException("Internet Explorer browser window for '" +
                    this.windowIdentifier + "' not found!");
            }
            // If so, wait for load
            //
            else
            {
                while (ie.ReadyState != tagREADYSTATE.READYSTATE_COMPLETE)
                {
                    Thread.Sleep(100);
                }
            }

            // Retrieve mshtml.Document from mshtml.InternetExplorer
            //
            object objDoc = this.ie.Document;
            this.doc = (HTMLDocument)objDoc;
        }
Ejemplo n.º 46
0
		private static SHDocVw.InternetExplorer findInternetExplorer(BaseConstraint findBy)
		{
			ShellWindows allBrowsers = new ShellWindows();

			int browserCount = allBrowsers.Count;
			int browserCounter = 0;

			IEAttributeBag attributeBag = new IEAttributeBag();

			while (browserCounter < browserCount)
			{
				attributeBag.InternetExplorer = (SHDocVw.InternetExplorer) allBrowsers.Item(browserCounter);

				if (findBy.Compare(attributeBag))
				{
					return attributeBag.InternetExplorer;
				}

				browserCounter++;
			}

			return null;
		}
 private static InternetExplorer GetInternetExplorerInstance()
 {
     InternetExplorer ie;
     do
     {
         ShellWindows shellWindows = new ShellWindows(); ;
         ie = shellWindows.OfType<InternetExplorer>().FirstOrDefault(ieInstance => ieInstance.LocationURL == "about:Tabs");
     } while (ie == null);
     return ie;
 }
Ejemplo n.º 48
0
        public static void open_url(Browser b, bool incognito = false)
        {
            var args = new List<String>();
            if (incognito)
                args.Add(b.private_arg);
            args.Add(Program.url.Replace("\"", "%22"));

            if (b.exec == "edge")
            {
                //edge is a universal app , which means we can't just run it like other browsers
                Process.Start("microsoft-edge:" + Program.url
                    .Replace(" ", "%20")
                    .Replace("\"", "%22"));
            }
            else if (b.exec.EndsWith("iexplore.exe") && !incognito)
            {
                // IE tends to open in a new window instead of a new tab
                // code borrowed from http://stackoverflow.com/a/3713470/1461004
                bool found = false;
                ShellWindows iExplorerInstances = new ShellWindows();
                foreach (InternetExplorer iExplorer in iExplorerInstances)
                {
                    if (iExplorer.Name.EndsWith("Internet Explorer"))
                    {
                        iExplorer.Navigate(Program.url, 0x800);
                        // for issue #10 (bring IE to focus after opening link)
                        ForegroundAgent.RestoreWindow(iExplorer.HWND);
                        found = true;
                        break;
                    }
                }
                if (!found)
                    Process.Start(b.exec, Program.Args2Str(args));
            }
            else
                Process.Start(b.exec, Program.Args2Str(args));

            Application.Exit();
        }
        private static string RetrieveAccessCode(string authorizationUrl)
        {
            Process.Start("iexplore", authorizationUrl);
            string appKey = null;
            var shellWindows = new ShellWindows();
            var htmlDocument = new HtmlDocument();
            var ie = GetInternetExplorerInstance(shellWindows);

            var document = ie.Document as HTMLDocument;

            if (document != null)
            {
                HtmlNode elementById = null;
                while (document.readyState != "complete" || elementById == null || !ie.LocationURL.Contains("accounts.google.com/o/oauth2/approval"))
                {
                    htmlDocument.LoadHtml(document.documentElement.innerHTML);
                    elementById = htmlDocument.GetElementById("code");
                    Thread.Sleep(500);
                }
                appKey = elementById.Attributes["value"].Value;
            }

            ie.Quit();
            return appKey;
        }
 private static InternetExplorer GetInternetExplorerInstance(ShellWindows shellWindows)
 {
     var ie = shellWindows.OfType<InternetExplorer>().FirstOrDefault(ieInstance => ieInstance.LocationURL.Contains("accounts.google.com/o/oauth2"));
     while (ie == null)
         ie = shellWindows.OfType<InternetExplorer>().FirstOrDefault(ieInstance => ieInstance.LocationURL.Contains("accounts.google.com/o/oauth2"));
     return ie;
 }
Ejemplo n.º 51
0
        private InternetExplorer LauchBrowser()
        {
            string IELocation = @"C:\Program Files\Internet Explorer\iexplore.exe";
            IELocation = System.Environment.ExpandEnvironmentVariables(IELocation);

            //Console.WriteLine("Launching IE ");
            Process p = Process.Start(IELocation, "about:blank");
            //int handle = (int)p.MainWindowHandle;
            Thread.Sleep(3000);

            //Console.WriteLine("Attaching to IE ... ");
            InternetExplorer ie = null;
            try
            {
                //if (p != null)
                //{
                //Console.WriteLine("Process handle is: " + p.MainWindowHandle.ToString());
                SHDocVw.ShellWindows allBrowsers = new ShellWindows();
                //Console.WriteLine("Number of active IEs :" + allBrowsers.Count.ToString());
                if (allBrowsers.Count != 0)
                {
                    for (int i = 0; i < allBrowsers.Count; i++)
                    {
                        InternetExplorer e = (InternetExplorer)allBrowsers.Item(i);
                        if (e != null)
                        {
                            if (e.LocationURL == "about:blank")
                            //if (e.HWND == (int)p.MainWindowHandle)
                            {
                                ie = e;
                                break;
                            }
                        }
                    }
                }
                else
                    throw new Exception("Faul to find IE");
                //}
                //else
                //    throw new Exception("Fail to launch IE");
            }
            catch (Exception e)
            {
                throw e;
            }
            return ie;
        }