コード例 #1
4
ファイル: WindowMgr.cs プロジェクト: millsy/Process-Capture
        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";
        }
コード例 #2
0
		private void populateBrowserCheckedBox()
		{
			ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
			foreach (InternetExplorer Browser in m_IEFoundBrowsers)
			{
				int index = 0;

                try
                {
                    if (Browser.Document != null && Browser.Document is mshtml.HTMLDocument)
                    {
                        string title = ((mshtml.HTMLDocument)Browser.Document).title;
                        if (browserList.Contains(title))
                        {
                            foreach (string a in browserList)
                            {
                                if (a.Equals(title)) index++;
                            }
                        }
                        browserCheckedListBox.Items.Add(((mshtml.HTMLDocument)Browser.Document).title + " - Index: " + index);
                        browserList.Add(((mshtml.HTMLDocument)Browser.Document).title);
                        indexes.Add(index);
                    }
                }
                catch (System.Runtime.InteropServices.COMException) { continue; }
			}
			if (browserCheckedListBox.Items.Count == 0) attachBrowserButton.Enabled = false;
		}
コード例 #3
0
        public InternetExplorer GetIEBrowser(string processName, string url)
        {
            Process[] pList = Process.GetProcessesByName(processName);
            foreach (Process proc in pList)
            {
                if (proc.ProcessName == processName)
                {
                    ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
                    foreach (InternetExplorer Browser in m_IEFoundBrowsers)
                    {
                        string chkUrl = Browser.LocationURL;
                        if (chkUrl == url)
                        {
                            if (Browser.HWND == (int)proc.MainWindowHandle)
                            {
                                _IE = Browser;
                                return(Browser);

                                break;
                            }
                        }
                    }
                }
            }
            return(null);
        }
コード例 #4
0
        //Code taken from http://omegacoder.com/?p=63
        private List<InternetExplorer> GetAllExplorers()
        {
            ShellWindows shellWindows = new ShellWindowsClass();

            List<InternetExplorer> explorers = shellWindows.OfType<InternetExplorer>().Where(IsWindowsExplorer).ToList();

            return explorers;
        }
コード例 #5
0
    private static IEnumerable <InternetExplorer> GetInternetExplorers()
    {
        ShellWindows                   shellWindows      = new ShellWindowsClass();
        List <InternetExplorer>        allExplorers      = shellWindows.Cast <InternetExplorer>().ToList();
        IEnumerable <InternetExplorer> internetExplorers = allExplorers.Where(ie => Path.GetFileNameWithoutExtension(ie.FullName).ToLower() == "iexplore");

        return(internetExplorers);
    }
コード例 #6
0
        //Code taken from http://omegacoder.com/?p=63
        private List <InternetExplorer> GetAllExplorers()
        {
            ShellWindows shellWindows = new ShellWindowsClass();

            List <InternetExplorer> explorers = shellWindows.OfType <InternetExplorer>().Where(IsWindowsExplorer).ToList();

            return(explorers);
        }
コード例 #7
0
 private void CloseInternetExplorer()
 {
     ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
     foreach (SHDocVw.InternetExplorer ie in m_IEFoundBrowsers)
     {
         try { ie.Quit(); }
         catch { }
     }
 }
コード例 #8
0
    private void OpenWindows_Load(object sender, EventArgs e)
    {      
      ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
      
      foreach (SHDocVw.InternetExplorer Browser in m_IEFoundBrowsers)
      {
        if(Browser.FullName.ToLower().Contains("iexplore.exe"))
          listBox1.Items.Add(Browser.LocationName);

      //  mshtml.HTMLDocument doc = (mshtml.HTMLDocument)Browser.Document;

      //  foreach(mshtml.HTMLDialog dialog in Browser.)
      }
    }
コード例 #9
0
        public static mshtml.HTMLDocument GetDocumentByAddress(this SHDocVw.ShellWindowsClass shell, string address)
        {
            var wbSearched = new ShellWindowsClass().Cast <IWebBrowser2>().FirstOrDefault(x => x.LocationURL.ToLower().Contains(address.ToLower()));

            if (wbSearched == null)
            {
                return(null);
            }
            if (!(wbSearched.Document is mshtml.HTMLDocument))
            {
                return(null);
            }

            return((mshtml.HTMLDocument)wbSearched.Document);
        }
コード例 #10
0
        public static mshtml.HTMLDocument GetDocumentByPtr(this SHDocVw.ShellWindowsClass shell, IntPtr pointer)
        {
            var wbSearched = new ShellWindowsClass().Cast <IWebBrowser2>().FirstOrDefault(x => x.HWND == (int)pointer);

            if (wbSearched == null)
            {
                return(null);
            }
            if (!(wbSearched.Document is mshtml.HTMLDocument))
            {
                return(null);
            }

            return((mshtml.HTMLDocument)wbSearched.Document);
        }
コード例 #11
0
        /// <summary>
        /// 获取 IE 进程窗口对象
        /// </summary>
        /// <returns></returns>
        private InternetExplorer GetIEWindow()
        {
            ShellWindowsClass shellWindows = new ShellWindowsClass();

            foreach (InternetExplorer ie in shellWindows)
            {
                if (ie.FullName.ToUpper().IndexOf("IEXPLORE.EXE") > 0)
                {
                    // 找到 IE 浏览器窗口
                    return(ie);
                }
            }

            return(null);
        }
コード例 #12
0
ファイル: IEHelper.cs プロジェクト: hanksoft/KillJD
 /// <summary>
 /// 获取IE全部网址
 /// </summary>
 /// <returns></returns>
 public List<WebSiteModel> MonitorIE()
 {
     try
     {
         ShellWindowsClass shellWindows = new ShellWindowsClass();
         List<WebSiteModel> ieUrls = new List<WebSiteModel>();
         foreach (InternetExplorer ie in shellWindows)
         {
             ieUrls.Add(new WebSiteModel() { url = ie.LocationURL, title = ie.LocationName });
         }
         return ieUrls;
     }
     catch
     {
         return null;
     }
 }
コード例 #13
0
        public static List <InternetExplorer> ieInstances()
        {
            var          ieInstances  = new List <InternetExplorer>();
            ShellWindows shellWindows = new ShellWindowsClass();

            for (int i = 0; i < shellWindows.Count; i++)
            {
                if (shellWindows.Item(i) is InternetExplorer)
                {
                    var instance = (InternetExplorer)shellWindows.Item(i);
                    //make sure it is a browser instance (since we don't want the Windows Explorer cases)
                    if (instance.FullName.contains("IEXPLORE.EXE"))
                    {
                        ieInstances.Add(instance);
                    }
                }
            }
            return(ieInstances);
        }
コード例 #14
0
 /// <summary>
 /// 获取IE全部网址
 /// </summary>
 /// <returns></returns>
 public List <WebSiteModel> MonitorIE()
 {
     try
     {
         ShellWindowsClass   shellWindows = new ShellWindowsClass();
         List <WebSiteModel> ieUrls       = new List <WebSiteModel>();
         foreach (InternetExplorer ie in shellWindows)
         {
             ieUrls.Add(new WebSiteModel()
             {
                 url = ie.LocationURL, title = ie.LocationName
             });
         }
         return(ieUrls);
     }
     catch
     {
         return(null);
     }
 }
コード例 #15
0
        public IEDriver()
        {
            Process m_Proc = Process.Start("IExplore.exe");

            Thread.Sleep(500);
            _IE = null;
            ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();

            foreach (InternetExplorer Browser in m_IEFoundBrowsers)
            {
                if (Browser.HWND == (int)m_Proc.MainWindowHandle)
                {
                    _IE = Browser;
                    break;
                }
            }

            IE.Visible           = true;
            IE.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);
        }
コード例 #16
0
        private string GetExplorerPath()
        {
            try
            {
                ShellWindows shellWindows     = new ShellWindowsClass();
                int          foregroundHandle = GetForegroundWindow().ToInt32();
                ExplorerHandle = foregroundHandle;

                foreach (InternetExplorer ie in shellWindows)
                {
                    if (ie.HWND == foregroundHandle)
                    {
                        return(((IShellFolderViewDual2)ie.Document).FocusedItem.Path);
                    }
                }
            }
            catch (Exception)
            {
                return(null);
            }
            return(null);
        }
コード例 #17
0
        // Comment out this method and we have an alternative solution.
        //private static SUIIE GetIE()
        //{
        //    Object o = Interaction.CreateObject("Shell.Application.1", null);
        //    IShellDispatch4 shell = (IShellDispatch4)o;
        //    IShellWindows windows = (IShellWindows)shell.Windows();
        //    for (int i = 0; i < windows.Count; i++)
        //    {
        //        Object obj = windows.Item(i);

        //        if (Information.TypeName(obj).Equals("IWebBrowser2"))
        //        {
        //            IWebBrowser2 browser = (IWebBrowser2)obj;
        //            SUIWindow ieWin = new SUIWindow(new IntPtr(browser.HWND));
        //            if (ieWin.WindowText.Contains(IETitleSuffix))
        //            {
        //                SUIIE instance = new SUIIE(browser);
        //                instance.ieWin = ieWin;
        //                return instance;
        //            }
        //        }
        //    }
        //    return null;
        //}

        public static SUIIE WaitingForIEWindow(string IETitle)
        {
            // Interestingly, we cannot catch IE7 window with below logic on Vista
            // without Administrative previlege.
            ShellWindows windows = new ShellWindowsClass();
            int          count   = windows.Count;

            InternetExplorer myIE = null;

            while (myIE == null)
            {
                SUISleeper.Sleep(1000);
                if (windows.Count >= count + 1)
                {
                    foreach (InternetExplorer tmpIE in windows)
                    {
                        if (tmpIE.FullName.EndsWith(IEProcess, true, null))
                        {
                            myIE = tmpIE;
                        }
                    }
                }
            }

            SUIIE ie = new SUIIE(myIE);

            ie.ieWin = new SUIWindow(new IntPtr(myIE.HWND));

            if (ie.WaitingForLoadComplete())
            {
                //If the specified title is a null string, we will return the default IE window we find.
                if (IETitle == null || ie.IEWin.WindowText.Equals(IETitle + SUIIE.IETitleSuffix))
                {
                    ie.IEWin.Maximized = true;
                    return(ie);
                }
            }
            return(null);
        }
コード例 #18
0
        /// <summary>
        /// 判断网页是否已经打开,已经打开则返回true
        /// </summary>
        /// <param name="url"></param>
        /// <param name="bro">返回对打开的网页的引用</param>
        /// <returns></returns>
        public bool IsOpened(string url, out InternetExplorer bro)
        {
            bro = null;
            try
            {
                ShellWindows shellwindows = new ShellWindowsClass();

                foreach (InternetExplorer browser in shellwindows)
                {
                    if (browser.LocationURL.Contains(url))
                    {
                        bro = browser;
                        return(true);
                    }
                }
            }
            catch
            {
                return(false);
            }
            return(false);
        }
コード例 #19
0
        /// <summary>
        /// Attempts to attach to an existing browser.
        /// </summary>
        /// <returns>An instance of an Internet Explorer browser.</returns>
        public static InternetExplorerBrowser Attach()
        {
            var foundBrowsers = new ShellWindowsClass().Cast <InternetExplorer>()
                                .Where(x => x.FullName.Contains("IEXPLORE.EXE"))
                                .ToList();

            if (foundBrowsers.Count <= 0)
            {
                return(null);
            }

            var foundBrowser = foundBrowsers.FirstOrDefault(x => x.Visible && x.HWND != 0);

            if (foundBrowser == null)
            {
                return(null);
            }

            var browser = new InternetExplorerBrowser(foundBrowser);

            browser.Refresh();
            return(browser);
        }
コード例 #20
0
ファイル: IEDriver.cs プロジェクト: ScoreSolutions/DLT-SCAN
        public IEDriver()
        {
            Process m_Proc = Process.Start("IExplore.exe");
            try {
                Thread.Sleep(1000);
                _IE = null;
                ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
                foreach(InternetExplorer Browser in m_IEFoundBrowsers) {
                    if(Browser.HWND == (int)m_Proc.MainWindowHandle) {
                        _IE = Browser;
                        break;
                    }
                }

                IE.Visible = true;
                IE.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);
                m_Proc.Close();
                m_Proc.Dispose();
            }catch(Exception ex){
                _err = ex.Message;
                CloseAllIE();
            }
        }
コード例 #21
0
        private static SHDocVw.InternetExplorer GetBrowserToAttachTo(int processId = 0)
        {
            var explorers = new ShellWindowsClass()
                            .Cast <SHDocVw.InternetExplorer>()
                            .Where(x => x.FullName.ToLower().Contains("iexplore.exe"))
                            .ToList();

            foreach (var explorer in explorers)
            {
                try
                {
                    if (processId > 0)
                    {
                        uint foundProcessId;
                        if (!NativeMethods.GetWindowThreadProcessId(new IntPtr(explorer.HWND), out foundProcessId) || foundProcessId != processId)
                        {
                            continue;
                        }
                    }

                    using (var browser = new InternetExplorer(explorer))
                    {
                        LogManager.Write($"Found browser with id of {browser.Id} at location {browser.Uri}.", LogLevel.Verbose);
                    }

                    return(explorer);
                }
                catch (Exception ex)
                {
                    // Ignore this browser and move to the next one.
                    LogManager.Write($"Error with finding browser to attach to. Exception: {ex.Message}.", LogLevel.Verbose);
                }
            }

            return(null);
        }
コード例 #22
0
        public static void TakeScreenShot()
        {
            // Thread.Sleep(20000);


            WebBrowser m_browser = null;

            ShellWindows shellWindows = new ShellWindowsClass();

            //Find first availble browser window.
            //Application can easily be modified to loop through and capture all open windows.
            string filename;

            foreach (SHDocVw.WebBrowser ie in shellWindows)
            {
                filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();

                if (filename.Equals("iexplore"))
                {
                    m_browser = ie;
                    break;
                }
            }

            //Assign Browser Document
            mshtml.IHTMLDocument2 myDoc = (mshtml.IHTMLDocument2)m_browser.Document;
            mshtml.IHTMLDocument3 doc3  = (mshtml.IHTMLDocument3)myDoc;
            int heightsize   = 0;
            int widthsize    = 0;
            int screenHeight = 0;
            int screenWidth  = 0;


            //if (!IsDTDDocument(myDoc))
            //{
            //    myDoc.body.setAttribute("scroll", "Yes", 0);

            //    //Get Browser Window Height
            //    heightsize = (int)myDoc.body.getAttribute("scrollHeight", 0);
            //    widthsize = (int)myDoc.body.getAttribute("scrollWidth", 0);

            //    //Get Screen Height
            //    screenHeight = (int)myDoc.body.getAttribute("clientHeight", 0);
            //    screenWidth = (int)myDoc.body.getAttribute("clientWidth", 0);
            //}
            //else
            {
                doc3.documentElement.setAttribute("scroll", "Yes", 0);

                //Get Browser Window Height
                heightsize = (int)doc3.documentElement.getAttribute("scrollHeight", 0);
                widthsize  = (int)doc3.documentElement.getAttribute("scrollWidth", 0);

                //Get Screen Height
                screenHeight = (int)doc3.documentElement.getAttribute("clientHeight", 0);
                screenWidth  = (int)doc3.documentElement.getAttribute("clientWidth", 0);
            }

            //Get bitmap to hold screen fragment.
            Bitmap bm = new Bitmap(screenWidth, screenHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);

            //Create a target bitmap to draw into.
            Bitmap bm2 = new Bitmap(widthsize, heightsize,
                                    System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
            Graphics g2 = Graphics.FromImage(bm2);

            Graphics g = null;
            IntPtr   hdc;
            Image    screenfrag = null;
            int      brwTop     = 0;
            int      brwLeft    = 0;
            int      myPage     = 0;
            IntPtr   myIntptr   = (IntPtr)m_browser.HWND;
            //Get inner browser window.
            int    hwndInt = myIntptr.ToInt32();
            IntPtr hwnd    = myIntptr;

            hwnd = GetWindow(hwnd, GW_CHILD);
            StringBuilder sbc = new StringBuilder(256);

            //Get Browser "Document" Handle
            while (hwndInt != 0)
            {
                hwndInt = hwnd.ToInt32();
                GetClassName(hwndInt, sbc, 256);

                if (sbc.ToString().IndexOf("Shell DocObject View", 0) > -1) // pre-IE7
                {
                    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", IntPtr.Zero);
                    break;
                }

                if (sbc.ToString().IndexOf("TabWindowClass", 0) > -1) // IE7
                {
                    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell DocObject View", IntPtr.Zero);
                    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", IntPtr.Zero);
                    break;
                }

                if (sbc.ToString().IndexOf("Frame Tab", 0) > -1) // IE8
                {
                    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "TabWindowClass", IntPtr.Zero);
                    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell DocObject View", IntPtr.Zero);
                    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", IntPtr.Zero);
                    break;
                }
                hwnd = GetWindow(hwnd, GW_HWNDNEXT);
            }

            //Get Screen Height (for bottom up screen drawing)
            while ((myPage * screenHeight) < heightsize)
            {
                //if (!IsDTDDocument(myDoc))
                //    myDoc.body.setAttribute("scrollTop", (screenHeight - 5) * myPage, 0);
                //else
                doc3.documentElement.setAttribute("scrollTop", (screenHeight - 5) * myPage, 0);
                ++myPage;
            }
            //Rollback the page count by one
            --myPage;

            int myPageWidth = 0;

            while ((myPageWidth * screenWidth) < widthsize)
            {
                //if (!IsDTDDocument(myDoc))
                //    myDoc.body.setAttribute("scrollLeft", (screenWidth - 5) * myPageWidth, 0);
                //else
                doc3.documentElement.setAttribute("scrollLeft", (screenWidth - 5) * myPageWidth, 0);
                //if (!IsDTDDocument(myDoc))
                //    brwLeft = (int)myDoc.body.getAttribute("scrollLeft", 0);
                //else
                brwLeft = (int)doc3.documentElement.getAttribute("scrollLeft", 0);
                for (int i = myPage; i >= 0; --i)
                {
                    //Shoot visible window
                    g   = Graphics.FromImage(bm);
                    hdc = g.GetHdc();
                    //if (!IsDTDDocument(myDoc))
                    //    myDoc.body.setAttribute("scrollTop", (screenHeight - 5) * i, 0);
                    //else
                    doc3.documentElement.setAttribute("scrollTop", (screenHeight - 5) * i, 0);

                    //if (!IsDTDDocument(myDoc))
                    //    brwTop = (int)myDoc.body.getAttribute("scrollTop", 0);
                    //else
                    brwTop = (int)doc3.documentElement.getAttribute("scrollTop", 0);
                    PrintWindow(hwnd, hdc, 0);
                    g.ReleaseHdc(hdc);
                    g.Flush();
                    screenfrag = Image.FromHbitmap(bm.GetHbitmap());
                    g2.DrawImage(screenfrag, brwLeft, brwTop);
                }
                ++myPageWidth;
            }

            //Reduce Resolution Size
            double   myResolution = Convert.ToDouble(100) * 0.01;
            int      finalWidth   = (int)((widthsize) * myResolution);
            int      finalHeight  = (int)((heightsize) * myResolution);
            Bitmap   finalImage   = new Bitmap(finalWidth, finalHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
            Graphics gFinal       = Graphics.FromImage((Image)finalImage);

            gFinal.DrawImage(bm2, 0, 0, finalWidth, finalHeight);

            //Get Time Stamp
            DateTime myTime = DateTime.Now;
            String   format = "MM.dd.hh.mm.ss";

            //Create Directory to save image to.
            Directory.CreateDirectory("D:\\IECapture");

            //Write Image.
            EncoderParameters eps = new EncoderParameters(1);

            eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Convert.ToInt64(100));
            ImageCodecInfo ici = GetEncoderInfo("image/jpeg");

            finalImage.Save(@"D:\\IECapture\Captured_" + myTime.ToString(format) + ".jpg", ici, eps);

            //Clean Up.
            myDoc = null;
            g.Dispose();
            g2.Dispose();
            gFinal.Dispose();
            bm.Dispose();
            bm2.Dispose();
            finalImage.Dispose();
        }
コード例 #23
0
        private void button3_Click(object sender, EventArgs e)
        {
            //查找打开的窗口句柄
            int iehwnd = FindWindowA("IEFrame", "百度一下,你就知道 - Internet Explorer");

            //初始化所有IE窗口
            IShellWindows sw = new ShellWindowsClass();

            //轮询所有IE窗口
            for (int i = sw.Count - 1; i >= 0; i--)
            {
                //得到每一个IE的 IWebBrowser2 对象
                IWebBrowser2 iwb2 = sw.Item(i) as IWebBrowser2;
                //比对 得到的 句柄是否符合查找的窗口句柄
                if (iwb2.HWND == iehwnd)
                {
                    //查找成功 进行赋值
                    document = (HTMLDocumentClass)iwb2.Document;
                    //对网页进行操作
                    document.getElementById("kw").setAttribute("value", "1111");
                    //document.getElementById("kw").onclick();
                }
            }
            //IntPtr parent = FindWindow("IEFrame", null);
            //int child = FindWindowEx(parent.ToInt32(), 0, "Frame Tab", null);
            //child = FindWindowEx(child, 0, "TabWindowClass", null);
            //child = FindWindowEx(child, 0, "Shell DocObject View", null);
            //child = FindWindowEx(child, 0, "Internet Explorer_Server", null);

            ////var oBrowser = DiagnosticsGlobalScope.browser;
            //IHTMLDocument2 doc =(IHTMLDocument2)GetDocument(child);
            //MessageBox.Show(doc.title);
            //IHTMLElement2 elm=(IHTMLElement2)doc.all.item("wd",0);
            //MessageBox.Show(elm.ToString());
            //FramesCollection frames= doc.frames;
            ////if (frames.length > 0)
            ////{
            ////    for(int i = 0; i < frames.length; i++)
            ////    {
            ////        IHTMLWindow2 window=frames.item(i);
            ////    }
            ////}
            //IHTMLElementCollection coll = doc.forms;
            //if (coll.length > 0)
            //{
            //    for (int i = 0; i < coll.length; i++)
            //    {
            //        IHTMLElement window = coll.item(i);
            //        string name=window.getAttribute("name");
            //        if (name == "wd")
            //        {
            //            window.setAttribute("value", "1");
            //        }
            //    }
            //}
            //IHTMLDOMChildrenCollection collect = (IHTMLDOMChildrenCollection)doc.childNodes;

            //foreach (IHTMLDOMNode node in collect)
            //{
            //    //因为关闭节点也会有(比如</a>,但是这样的节点会被定义为HTMLUnknownElementClass)
            //    //所以要判断这个节点是不是未知节点不是才处理
            //    if (!(node is IHTMLUnknownElement))
            //    {

            //        //获取属性集合
            //        IHTMLAttributeCollection attrs = (IHTMLAttributeCollection)node.attributes;
            //        foreach (IHTMLDOMAttribute attr in attrs)
            //        {

            //            //只有specified=true的属性才是你要的
            //            if (attr.specified)
            //            {
            //                Console.Write(attr.nodeValue);
            //            }
            //        }
            //    }
            //}
        }
コード例 #24
0
ファイル: IEDriver.cs プロジェクト: DougThompson/AutomateIE
        /// <summary>
        /// Constructor to attach automation object
        /// </summary>
        /// <param name="attachToExisting"></param>
        /// <param name="pageName"></param>
        /// <param name="pageTitle"></param>
        /// <param name="TextBox1"></param>
        public IEDriver(bool attachToExisting, string pageName, string pageTitle, RichTextBox TextBox1)
        {
            // Setup some local variables
            textBox1 = TextBox1;
            int hwnd = -1;
            ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
            _IE = null;

            // Start a stopwatch for timeout issues
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            while (_IE == null & stopWatch.Elapsed.TotalSeconds < 60)
            {
                // Determine how to attach -- Existing or new
                // When starting a new test, best not to attach
                if (!attachToExisting)
                {
                    if (m_IEFoundBrowsers.Count <= 1)
                    {
                        _Proc = Process.Start("IExplore.exe");

                        Thread.Sleep(1000);
                        hwnd = (int)_Proc.MainWindowHandle;
                    }

                    foreach (InternetExplorer Browser in m_IEFoundBrowsers)
                    {
                        if (_Proc != null)
                        {
                            if (Browser.HWND == hwnd)
                            {
                                _IE = Browser;
                                break;
                            }
                        }
                        else
                        {
                            //Try to attach to an existing browser window
                            HTMLDocument doc = Browser.Document as HTMLDocument;
                            if (doc != null)
                            {
                                _IE = Browser;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    foreach (InternetExplorer Browser in m_IEFoundBrowsers)
                    {
                        if (_Proc != null)
                        {
                            if (Browser.HWND == hwnd)
                            {
                                _IE = Browser;
                                break;
                            }
                        }
                        else
                        {
                            //Try to attach to an existing browser window
                            HTMLDocument doc = Browser.Document as HTMLDocument;
                            if (doc != null)
                            {
                                string url = doc.URLUnencoded;
                                url = url.Substring(url.LastIndexOf("/") + 1);
                                if (url.IndexOf("?") >= 0)
                                    url = url.Substring(0, url.IndexOf("?"));

                                if (doc.title.Equals(pageTitle ?? "", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    printTestResult(textBox1, "Attaching to", String.Format("{0}   {1}{2}", Environment.NewLine, pageTitle, Environment.NewLine));
                                    _IE = Browser;
                                    break;
                                }

                                if (url.Equals(pageName ?? "", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    printTestResult(textBox1, "Attaching to", String.Format("{0}   {1}{2}", Environment.NewLine, pageName, Environment.NewLine));
                                    _IE = Browser;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (_IE == null & stopWatch.Elapsed.TotalSeconds > 60)
                throw new Exception("IE did not load within 60 seconds.");

            if (_IE == null)
                throw new Exception("IE did not load.");

            IE.Visible = true;
            IE.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);
        }
コード例 #25
0
ファイル: InternetExplorer.cs プロジェクト: BobbyCannon/TestR
        private static SHDocVw.InternetExplorer GetBrowserToAttachTo(int processId = 0)
        {
            var explorers = new ShellWindowsClass()
                .Cast<SHDocVw.InternetExplorer>()
                .Where(x => x.FullName.ToLower().Contains("iexplore.exe"))
                .ToList();

            foreach (var explorer in explorers)
            {
                try
                {
                    if (processId > 0)
                    {
                        uint foundProcessId;
                        if (!NativeMethods.GetWindowThreadProcessId(new IntPtr(explorer.HWND), out foundProcessId) || (foundProcessId != processId))
                        {
                            continue;
                        }
                    }

                    using (var browser = new InternetExplorer(explorer))
                    {
                        //LogManager.Write($"Found browser with id of {browser.Id} at location {browser.Uri}.", LogLevel.Verbose);
                    }

                    return explorer;
                }
                catch (Exception)
                {
                    // Ignore this browser and move to the next one.
                    //LogManager.Write($"Error with finding browser to attach to. Exception: {ex.Message}.", LogLevel.Verbose);
                }
            }

            return null;
        }
コード例 #26
0
		private void checkAttach()
		{
			if (HTMLEvents.lastBrowser != browserId)
			{
				if (String.IsNullOrEmpty(ie.LocationName)) return;

				int index = 0;
				string title = ((mshtml.HTMLDocument)ie.Document).title;
				ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
				foreach (InternetExplorer Browser in m_IEFoundBrowsers)
				{
					if (Browser.Document is mshtml.HTMLDocument)
					{
						if (((HTMLDocument)(Browser.Document)).title.Equals(title))
						{
							if ((Browser.GetProperty("ID") != null))
							{
								if (((int)Browser.GetProperty("ID")) == ((int)ie.GetProperty("ID"))) break;
							}
							index++;
						}
					}
				}

				_writer.AttachBrowser(ie.LocationName, index);
				HTMLEvents.lastBrowser = browserId;
			}



		}
コード例 #27
0
        private void attachToBrowser(int waitTime, string titleContents, int index)
        {
            string windowTitleLowerCase = setUpPDFExtentions(titleContents).ToLower();

            HTMLDocument ourDoc = null;
            IntPtr winHndle = IntPtr.Zero;
            SHDocVw.InternetExplorer oldBrowser = currentIEBrowser;
            currentIEBrowser = null;
            _attachedToModalDialog = false;
            int indexCount = 0;

            DateTime timeout = DateTime.Now.AddSeconds(waitTime);

            while (DateTime.Now < timeout)
            {
                //we must reset indexCount every iteration of this loop
                indexCount = 0;
                ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
                foreach (SHDocVw.InternetExplorer browser in m_IEFoundBrowsers)
                {
                    try
                    {
                        if (browser.Name.Equals(ieBrowserName))
                        {
                            // Check if browser is the one we are looking for
                            if (browserTitleIsMatch(browser, windowTitleLowerCase))
                            {
                                if (indexCount == index)
                                {
                                    currentIEBrowser = browser;
                                    curWindowHandle = new IntPtr(currentIEBrowser.HWND);
                                    if (browser.Type.Contains("PDF"))
                                    {
                                        return; // We are done here
                                    }
                                    break;
                                }
                                else
                                {
                                    indexCount++;
                                }
                            }
                        }
                    }
                    catch (COMException)
                    {
                        // A window was manually closed while iterating through ShellWindows
                        continue;
                    }
                }

                //if currentIEBrowser is null, then we havent found any browser windows...so check dialogs
                if (currentIEBrowser != null)
                    ourDoc = (mshtml.HTMLDocument)currentIEBrowser.Document;
                else
                    attachToModalDialog(titleContents, index, indexCount, ref ourDoc);

                //if the doc isn't null but the browser is, we have found a dialog, reassign the browser to the previous one
                if (ourDoc != null)
                {
                    if (currentIEBrowser == null)
                    {
                        _attachedToModalDialog = true;
                        currentIEBrowser = oldBrowser;
                    }
                    break;
                }
            }

            if (ourDoc == null)
            {
                if (indexCount == 0)
                    throw new WindowNotFoundException(titleContents);

                string message;
                if (indexCount == 1)
                    message = "There is only 1 window";
                else
                    message = "There are only " + indexCount + " windows";

                throw new IndexOutOfRangeException(message + " with " + titleContents + " in the title.");
            }

            setDocument(ourDoc);
            bringCurrentBrowserWindowToTop();
        }
コード例 #28
0
        public void KillAllOpenBrowsers(string windowTitle)
        {
            bool windowExists = false;
            string windowTitleLowerCase = setUpPDFExtentions(windowTitle).ToLower();

            ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
            Dictionary<SHDocVw.InternetExplorer, int> killedBrowsers = new Dictionary<SHDocVw.InternetExplorer, int>(m_IEFoundBrowsers.Count);

            // Need to iterate through ShellWindows multiple times in order to get all the windows.
            // Iterating through ShellWindows once or twice leaves a few windows open.
            // This may be because the open browsers may not have been registered with the ShellWindowsClass
            //  yet, in which it won't be visible to it
            for (int count = 10; count >= 0; count--)
            {
                // Refresh the ShellWindows list
                m_IEFoundBrowsers = new ShellWindowsClass();
                foreach (SHDocVw.InternetExplorer browser in m_IEFoundBrowsers)
                {
                    try
                    {
                        if (browser.Name.Equals(ieBrowserName) && !killedBrowsers.ContainsKey(browser))
                        {
                            // Check if browser is not the one we want to spare
                            if (!browserTitleIsMatch(browser, windowTitleLowerCase))
                            {
                                killedBrowsers.Add(browser, browser.HWND);
                                browser.Quit();
                            }
                            else
                                windowExists = true;

                            CoverCOMExceptionHandling();
                        }
                    }
                    catch (COMException)
                    {
                        // Someone manually closed a window while this was running.
                        continue;
                    }

                }
            }

            // If we have killed all the windows, we need to wait for the process to end
            if (!windowExists)
            {
                WaitForProcessesToEnd();
            }
            else   // Wait for each window we killed to close
            {
                foreach (int killedBrowserHandle in killedBrowsers.Values)
                {
                    WaitForWindowToClose(new IntPtr(killedBrowserHandle));
                }
            }
        }
コード例 #29
0
        private bool doesWindowExist(string windowTitle)
        {
            string windowTitleLowerCase = setUpPDFExtentions(windowTitle).ToLower();
            ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();

            foreach (SHDocVw.InternetExplorer browser in m_IEFoundBrowsers)
            {
                try
                {
                    if (browser.Name.Equals(ieBrowserName) && browserTitleIsMatch(browser, windowTitleLowerCase))
                        return true;
                }
                catch (COMException)
                {
                    // A window was manually closed while iterating through ShellWindows
                    continue;
                }
            }

            List<IntPtr> openWindowList = NativeMethods.GetAllOpenWindowsUnordered();
            StringBuilder className = new StringBuilder(255);

            // Looking for Modal Dialogs
            foreach (IntPtr intPtr in openWindowList)
            {
                NativeMethods.GetClassName(intPtr, className, className.MaxCapacity);
                if (NativeMethods.GetWindowText(intPtr).Contains(windowTitle) && className.ToString().StartsWith("Internet Explorer"))
                    return true;
            }

            // Window not found
            return false;
        }
コード例 #30
0
		public void JScriptPump()
		{
			while (_recording)
			{
				// polling time checking for JS box in ms
				Thread.Sleep(230);
				//Console.WriteLine("Thread Pump running...");

				// JScriptWindow Polling
				if (!JScriptWindowFound)
				{
					dialogHwnd = FindWindowByCaption(32770, "Microsoft Internet Explorer");
					if (dialogHwnd == IntPtr.Zero) {
						dialogHwnd = FindWindowByCaption(32770, "Windows Internet Explorer");
					} 

					// case the JavaScript window has been found. We need to attach a listener to it
					if (dialogHwnd != IntPtr.Zero)
					{
						Console.WriteLine("Window Found...");
						JScriptWindowFound = true;
						dialogHWnd_buttonOK = FindWindowEx(dialogHwnd, IntPtr.Zero, "Button", "OK");
						dialogHWnd_buttonCancel = FindWindowEx(dialogHwnd, IntPtr.Zero, "Button", "Cancel");
					}
				}

				// WARNING: TODO: create its own thread pump:Modal Window Polling
				modalWindowHwnd = GetForegroundWindow();
				if ((int)GetWindowText(modalWindowHwnd, Buff, nChars) > 0)
				{
					if (Buff.ToString().Contains("-- Webpage Dialog") && (!modalWindowFound))
					{
						Console.WriteLine("Modal Window Found: " + Buff.ToString());
						_writer.AttachBrowser(Buff.ToString(), 0);
						modalWindowFound = true;

						//_browser.AttachToWindow(Buff.ToString(), 0);
						//_inetExplorer = new WebBrowserEvents("PopUp", null, ref _writer);


						ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
						foreach (IWebBrowser2 Browser in m_IEFoundBrowsers)
						{

							if (Browser.Document is mshtml.HTMLDocument)
							{
								Console.WriteLine("found IE window: " + ((mshtml.HTMLDocument)Browser.Document).uniqueID + ", " + ((mshtml.HTMLDocument)Browser.Document).referrer + ", " + ((mshtml.HTMLDocument)Browser.Document).protocol);
								//if ((((mshtml.HTMLDocument)Browser.Document).title).Contains("-- Webpage Dialog"))
								if ((((mshtml.HTMLDocument)Browser.Document).title).Contains(""))
								{
									Console.WriteLine("Attempt to attach to modal window");
									_inetExplorer = new WebBrowserEvents("AttachToModalWindow", (InternetExplorer)Browser, ref _writer);
									//Console.WriteLine("doc: " + ((mshtml.HTMLDocument)Browser.Document).body.style.backgroundColor.ToString());
									break;
								}
							}
						}
					}
				}
			}
		}
コード例 #31
0
		public void Record(ContextMenuStrip cmsMenu, ArrayList browserNames, ArrayList indexes, System.Windows.Forms.CheckedListBox.CheckedIndexCollection checkedIndices)
		{
			this.InitializeContextMenu(cmsMenu);
			_writer = new SWATWikiGenerator();
			_writer.Initialize(BrowserType.InternetExplorer, false);
			_recording = true;

			RecordJScriptBoxSetup();

			foreach (int a in checkedIndices)
			{
				string titleContents = (String)browserNames[a];
				int _index = (int)indexes[a];
				int indexCount = 0;
				ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
				foreach (InternetExplorer Browser in m_IEFoundBrowsers)
				{
                    try
                    {
                        if (Browser.LocationName != "" && Browser.Document is mshtml.HTMLDocument)
                        {
                            if ((((mshtml.HTMLDocument)Browser.Document).title).Equals(titleContents))
                            {
                                if (indexCount == _index)
                                {
                                    _inetExplorer = new WebBrowserEvents("AttachToWindow", Browser, ref _writer);
                                    break;
                                }
                                else
                                    indexCount++;
                            }
                        }
                    }
                    catch (System.Runtime.InteropServices.COMException) { continue; }
				}
			}
		}
コード例 #32
0
 private void checkAttach()
 {
     if ((int)ie.GetProperty("ID") != lastBrowser)
     {
         if (String.IsNullOrEmpty(ie.LocationName)) return;
         int index = 0;
         string title = ((mshtml.HTMLDocument)ie.Document).title;
         ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
         foreach (SHDocVw.InternetExplorer Browser in m_IEFoundBrowsers)
         {
             if (Browser.Document is mshtml.HTMLDocument)
             {
                 if (((HTMLDocument)(Browser.Document)).title.Equals(title))
                 {
                     if ((Browser.GetProperty("ID") != null))
                     {
                         if (((int)Browser.GetProperty("ID")) == ((int)ie.GetProperty("ID"))) break;
                     }
                     index++;
                 }
             }
         }
         _builder.AttachBrowser(ie.LocationName, index);
         lastBrowser = (int)ie.GetProperty("ID");
         _previousClickedElement = null;
     }
 }
コード例 #33
0
ファイル: Form1.cs プロジェクト: nrother/fast-view
        private string GetExplorerPath()
        {
            try
            {
                ShellWindows shellWindows = new ShellWindowsClass();
                int foregroundHandle = GetForegroundWindow().ToInt32();
                ExplorerHandle = foregroundHandle;

                foreach (InternetExplorer ie in shellWindows)
                {
                    if (ie.HWND == foregroundHandle)
                    {
                        return ((IShellFolderViewDual2)ie.Document).FocusedItem.Path;
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
            return null;
        }
コード例 #34
0
ファイル: SUIIE.cs プロジェクト: a19284/SmartUI
        // Comment out this method and we have an alternative solution.
        //private static SUIIE GetIE()
        //{
        //    Object o = Interaction.CreateObject("Shell.Application.1", null);
        //    IShellDispatch4 shell = (IShellDispatch4)o;
        //    IShellWindows windows = (IShellWindows)shell.Windows();
        //    for (int i = 0; i < windows.Count; i++)
        //    {
        //        Object obj = windows.Item(i);

        //        if (Information.TypeName(obj).Equals("IWebBrowser2"))
        //        {
        //            IWebBrowser2 browser = (IWebBrowser2)obj;
        //            SUIWindow ieWin = new SUIWindow(new IntPtr(browser.HWND));
        //            if (ieWin.WindowText.Contains(IETitleSuffix))
        //            {
        //                SUIIE instance = new SUIIE(browser);
        //                instance.ieWin = ieWin;
        //                return instance;
        //            }
        //        }
        //    }
        //    return null;
        //}  

        public static SUIIE WaitingForIEWindow(string IETitle)
        {
            // Interestingly, we cannot catch IE7 window with below logic on Vista
            // without Administrative previlege.
            ShellWindows windows = new ShellWindowsClass();
            int count = windows.Count;

            InternetExplorer myIE = null;
            while (myIE == null)
            {
                SUISleeper.Sleep(1000);
                if (windows.Count >= count + 1)
                {
                    foreach (InternetExplorer tmpIE in windows)
                    {
                        if (tmpIE.FullName.EndsWith(IEProcess, true, null))
                        {
                            myIE = tmpIE;
                        }
                    }
                }
            }

            SUIIE ie = new SUIIE(myIE);
            ie.ieWin = new SUIWindow(new IntPtr(myIE.HWND));

            if (ie.WaitingForLoadComplete())
            {
                //If the specified title is a null string, we will return the default IE window we find.
                if (IETitle == null || ie.IEWin.WindowText.Equals(IETitle + SUIIE.IETitleSuffix))
                {
                    ie.IEWin.Maximized = true;
                    return ie;
                }
            }
            return null;
        }