예제 #1
0
        public static bool FCheckForControl(IHTMLDocument2 oDoc2, string sId)
        {
            if (oDoc2.all.item(sId, 0) != null)
                return true;

            return false;
        }
        /// <summary>
        /// Transform anchor tags to HtmlAnchorTag.
        /// </summary>
        /// <param name="htmlDoc"> The HTML DOM Document to process.</param>
        /// <returns> A HtmlTagBaseList.</returns>
        public static HtmlTagBaseList TransformAnchorElements(IHTMLDocument2 htmlDoc)
        {
            HtmlTagBaseList list = new HtmlTagBaseList();

            foreach ( object obj in htmlDoc.links )
            {
                if ( obj is IHTMLAnchorElement )
                {
                    IHTMLAnchorElement a = (IHTMLAnchorElement)obj;
                    HtmlAnchorTag anchorTag = new HtmlAnchorTag();
                    anchorTag.HRef = a.href;
                    anchorTag.Host = a.host;
                    anchorTag.Hostname = a.hostname;
                    anchorTag.MimeType = a.mimeType;
                    anchorTag.Pathname = a.pathname;
                    anchorTag.Protocol = a.protocol;
                    anchorTag.Query = a.search;
                    list.Add(anchorTag);
                }
            //				else
            //				{
            //					System.Windows.Forms.MessageBox.Show(((mshtml.IHTMLElement)obj).outerHTML);
            //				}
            }

            return list;
        }
예제 #3
0
		private static IHTMLDocument3 Transform( IHTMLDocument2 htmlDoc )
		{
			AddEmbeddedCSS( htmlDoc );
		
			// remove the onload InitTitle script call
			IHTMLBodyElement body = (IHTMLBodyElement)htmlDoc.body;
			body.onload = "";
			
			// because the scripts that insert the header and footer get
			// run when we load the source html, we remove them here
			// This also removes the dependency on having scripting enabled 
			// on client browsers for the online version
			foreach ( IHTMLDOMNode script in htmlDoc.scripts )
				script.parentNode.removeChild( script );

			IHTMLDocument3 doc3 = htmlDoc as IHTMLDocument3;
			Debug.Assert( doc3 != null );

			// fix up all of the hyper-links
			foreach ( IHTMLAnchorElement anchor in doc3.getElementsByTagName( "a" ) )
				Transform( anchor );

			// fix up all of the img tags
			foreach ( IHTMLImgElement img in doc3.getElementsByTagName( "img" ) )
				Transform( img );

			return doc3;
		}
        /// <summary>
        /// Try to extract the EditUri (RSD file URI) from the passed DOM
        /// </summary>
        /// <param name="weblogDOM"></param>
        /// <returns></returns>
        private static string ExtractEditUri(string homepageUrl, IHTMLDocument2 weblogDOM)
        {
            // look in the first HEAD tag
            IHTMLElementCollection headElements = ((IHTMLDocument3)weblogDOM).getElementsByTagName("HEAD");
            if (headElements.length > 0)
            {
                // get the first head element
                IHTMLElement2 firstHeadElement = (IHTMLElement2)headElements.item(0, 0);

                // look for link tags within the head
                foreach (IHTMLElement element in firstHeadElement.getElementsByTagName("LINK"))
                {
                    IHTMLLinkElement linkElement = element as IHTMLLinkElement;
                    if (linkElement != null)
                    {
                        string linkRel = linkElement.rel;
                        if (linkRel != null && (linkRel.ToUpperInvariant().Equals("EDITURI")))
                        {
                            return UrlHelper.UrlCombineIfRelative(homepageUrl, linkElement.href);
                        }
                    }
                }
            }

            // couldn't find one
            return null;
        }
예제 #5
0
        public void Filter(ref IHTMLDocument2 inputHtmlDoc)
        {
            try
            {
                //Modify input HTML document iff formName is valid
                if ((scriptNameByUrl != null) && (scriptNameByUrl.Trim().Length != 0))
                {
                    string JScript = "var scriptElement = null;                                         " +
                                     "var allScripts = document.scripts;                                " +
                                     "for(var index = 0; index < allScripts.length; index++)            " +
                                     "{                                                                 " +
                                     "    scriptElement = allScripts[index];                            " +
                                     "    if (scriptElement.src.toString().indexOf('" + scriptNameByUrl + "') >=0)   " +
                                     "    {                                                             " +
                                     "        alert(scriptElement.parentNode);      " +
                                     "    }                                                             " +
                                     "}                                                                 ";

                    //Hide the form
                    inputHtmlDoc.parentWindow.execScript(JScript, "JavaScript");

                }
            }
            catch
            {

            }
            finally
            {

            }
        }
예제 #6
0
        public static string GetCombinedUrl(IHTMLDocument2 docRoot, out int numOfDocs)
        {
            SortedDictionary<string, int> pageUrls = new SortedDictionary<string, int>();	// 중복삽입을 피하기 위해.
            string combinedUrl = "";

            IHTMLDocument2[] docs = ImgSrcExtractor.GetHtmlDocumentsByOle(docRoot);

            foreach (IHTMLDocument2 doc in docs)
            {
            //				Logger.DLog("page url found: {0}", doc.url);

                if (doc.url != "about:blank")
                {
                    if(!pageUrls.ContainsKey(doc.url))
                    {
                        pageUrls.Add(doc.url, 0);
                    }
                }
            }

            // combined url은 중복 삭제, 정렬 후 만든다.
            foreach(KeyValuePair<string, int> url in pageUrls)
            {
                combinedUrl += url.Key;
            }

            numOfDocs = pageUrls.Count;

            // 더이상 사용하지 않는다...
            numOfDocs = numOfDocs * 4 / 5;

            return combinedUrl;
        }
예제 #7
0
        protected virtual void WaitForFramesToComplete(IHTMLDocument2 maindocument)
        {
            var mainHtmlDocument = UtilityClass.GetWithFailOver(() => (HTMLDocument)maindocument);

            var framesCount = FrameCountProcessor.GetFrameCountFromHTMLDocument(mainHtmlDocument);

            for (var i = 0; i != framesCount; ++i)
            {
                var frame = FrameByIndexProcessor.GetFrameFromHTMLDocument(i, mainHtmlDocument);

                if (frame == null) continue;

                IHTMLDocument2 frameDocument;
                try
                {
                    if (!WaitWhileIEBusy(frame))
                        continue;

                    if (!WaitWhileIEReadyStateNotComplete(frame))
                        continue;

                    WaitWhileFrameDocumentNotAvailable(frame);

                    frameDocument = (IHTMLDocument2)frame.Document;
                }
                finally
                {
                    // free frame
                    Marshal.ReleaseComObject(frame);
                }

                WaitWhileDocumentStateNotCompleteOrInteractive(frameDocument);
                WaitForFramesToComplete(frameDocument);
            }
        }
        /// <summary>
        /// Transform each form element to a HtmlFormTag.
        /// </summary>
        /// <param name="htmlDoc"> The HTML DOM Document to process.</param>
        public static HtmlFormTagCollection TransformFormElements(IHTMLDocument2 htmlDoc, Uri currentUri)
        {
            // For each form, add in temp FormTags Collection
            FormConverter converter = new FormConverter();

            HtmlFormTagCollection formCollection = new HtmlFormTagCollection(htmlDoc.forms.length);

            try
            {
                foreach ( HTMLFormElementClass formElement in htmlDoc.forms )
                {
                    System.Windows.Forms.Application.DoEvents();

                    // Convert to HTML Form Tag
                    HtmlFormTag form = converter.ConvertToHtmlFormTag(formElement, currentUri);

                    if ( !formCollection.ContainsKey(form.Name) )
                    {
                        formCollection.Add(form.Name, form);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
                Microsoft.ApplicationBlocks.ExceptionManagement.ExceptionManager.Publish(ex);
            }

            return formCollection;
        }
        public void RefreshBehaviors(IHTMLDocument2 document)
        {
            lock(this)
            {
                // get interface needed for element enumeration
                IHTMLDocument3 document3 = (IHTMLDocument3)document ;

                // build new list of active behaviors
                Hashtable newActiveBehaviors = new Hashtable();

                //register global behaviors
                IDictionaryEnumerator behaviorEnumerator = _globalElementBehaviors.GetEnumerator() ;
                while (behaviorEnumerator.MoveNext())
                {
                    string tagName = (string)behaviorEnumerator.Key  ;
                    foreach( IHTMLElement element in document3.getElementsByTagName(tagName))
                    {
                        // if the element is already assigned an active behavior then move it
                        if ( _activeBehaviors.ContainsKey(element) )
                        {
                            newActiveBehaviors[element] = _activeBehaviors[element] ;
                            _activeBehaviors.Remove(element);
                        }
                        else // otherwise create a new behavior and add it
                        {
                            HtmlEditorElementBehavior elementBehavior = (HtmlEditorElementBehavior)Activator.CreateInstance(
                                (Type)behaviorEnumerator.Value, new object[] { element, _editorContext}  ) ;
                            newActiveBehaviors[element] = elementBehavior ;
                        }
                    }
                }

                //register element behaviors
                behaviorEnumerator = _elementBehaviors.GetEnumerator() ;
                while (behaviorEnumerator.MoveNext())
                {
                    IHTMLElement element = (IHTMLElement)behaviorEnumerator.Key  ;
                    // if the element is already assigned an active behavior then move it
                    if ( _activeBehaviors.ContainsKey(element) )
                    {
                        newActiveBehaviors[element] = _activeBehaviors[element] ;
                        _activeBehaviors.Remove(element);
                    }
                    else // otherwise create a new behavior and add it
                    {
                        Debug.Fail("illegal state: element behavior is not in the _activeBehaviors table");
                    }
                }

                // all of the elements left in the activeBehaviors list are no longer in the document
                // so we should dispose and remove them from the list
                foreach ( HtmlEditorElementBehavior elementBehavior in _activeBehaviors.Values )
                    elementBehavior.DetachFromElement();
                _activeBehaviors.Clear();

                // swap for new list
                _activeBehaviors = newActiveBehaviors ;
            }
        }
예제 #10
0
		public FrameCollection(DomContainer domContainer, IHTMLDocument2 htmlDocument)
		{
			AllFramesProcessor processor = new AllFramesProcessor(domContainer, (HTMLDocument) htmlDocument);

			NativeMethods.EnumIWebBrowser2Interfaces(processor);

			elements = processor.elements;
		}
예제 #11
0
파일: Document.cs 프로젝트: pusp/o2platform
		/// <summary>
		/// Initializes a new instance of the <see cref="Document"/> class.
		/// Mainly used by WatiN internally.
		/// </summary>
		/// <param name="domContainer">The DOM container.</param>
		/// <param name="htmlDocument">The HTML document.</param>
		public Document(DomContainer domContainer, IHTMLDocument2 htmlDocument)
		{
			ArgumentRequired(domContainer, "domContainer");
			ArgumentRequired(htmlDocument, "htmlDocument");

			DomContainer = domContainer;
			this.htmlDocument = htmlDocument;
		}
예제 #12
0
        public IEDocument(IHTMLDocument2 htmlDocument, IEElement containingFrameElement)
        {
            if (htmlDocument == null)
                throw new ArgumentNullException("htmlDocument");

            this.htmlDocument = htmlDocument;
            this.containingFrameElement = containingFrameElement;
        }
        /// <summary>
        /// initializes a class instance using the WLW editor handle to 
        /// obtain access to the current HTML document through IHTMLDocument2
        /// </summary>
        public WLWEditorContent(IntPtr wlwEditorHandle)
        {
            _owner = wlwEditorHandle;

            // Everything else in this class depends upon successful initialization of _htmlDocument
            _htmlDocument = WLWEditorContent.getHtmlDocument2(wlwEditorHandle);
            _anchorCollection = this.getAnchorCollection();
        }
예제 #14
0
 public DocHTML(HTMLDocument doc)
 {
     mDoc = doc;
     mDoc2 = (IHTMLDocument2)mDoc;
     mDoc3 = (IHTMLDocument3)mDoc;
     mDoc4 = (IHTMLDocument4)mDoc;
     mDoc5 = (IHTMLDocument5)mDoc;
 }
예제 #15
0
 public void UpdateDocumentEvents(IHTMLDocument2 document)
 {
     if (document != null)
     {
         //_document.MouseMove += new HtmlElementEventHandler(doc_MouseMove);
         //_document.Click += new HtmlElementEventHandler(doc_Click);
     }
 }
예제 #16
0
 public static int GetButtonElementIndex(IHTMLDocument2 doc, IHTMLElement ele, string itemName, string tagStr)
 {
     int num = 0;
     bool flag = false;
     if (ele != null)
     {
         ElementTag iD = ElementTag.ID;
         if ((tagStr != string.Empty) && (tagStr != ""))
         {
             iD = (ElementTag) WindowUtil.StringToInt(tagStr);
         }
         if (iD != ElementTag.ID)
         {
             IHTMLElementCollection o = (IHTMLElementCollection) doc.all.tags("input");
             foreach (IHTMLElement element in o)
             {
                 if ((IsElementMatchType(element, "submit") || IsElementMatchType(element, "button")) && IsElementMatch(element, iD, itemName, ""))
                 {
                     if (ele == element)
                     {
                         flag = true;
                         break;
                     }
                     num++;
                 }
             }
             if (o != null)
             {
                 Marshal.ReleaseComObject(o);
             }
             if (!flag)
             {
                 o = (IHTMLElementCollection) doc.all.tags("button");
                 foreach (IHTMLElement element2 in o)
                 {
                     if (IsElementMatch(element2, iD, itemName, ""))
                     {
                         if (ele == element2)
                         {
                             flag = true;
                             break;
                         }
                         num++;
                     }
                 }
                 if (o != null)
                 {
                     Marshal.ReleaseComObject(o);
                 }
             }
         }
     }
     if (!flag)
     {
         num = 0;
     }
     return num;
 }
예제 #17
0
        public Htmlwysiwyg()
        {
            InitializeComponent();
            _changed = false;
            try
            {
                if (HtmlRenderer.Document != null)
                {
                    _doc = (IHTMLDocument2) HtmlRenderer.Document.DomDocument;
                }
            }
            catch (Exception ex)
            {
                MessageDialog.Show
                    (
                        "htmlRenderer Exception  \r\n" + ex.InnerException,
                        "Error",
                        MessageDialog.MessageBoxButtons.Ok,
                        MessageDialog.MessageBoxIcon.Error,
                        "" + "\r\n" + ex.StackTrace);
            }
            if (_doc != null)
            {
                _doc.designMode = "On";
                while (_doc.body == null)
                {
                    Application.DoEvents();
                }
            }

            _custCtxMenu = new ContextMenuStrip();
            _custCtxMenu.Items.Add("&Copy");
            _custCtxMenu.Items.Add("&Cut");
            _custCtxMenu.Items.Add("&Paste");
            _custCtxMenu.ItemClicked += custCtxMenu_ItemClicked;
            try
            {
                if (HtmlRenderer.Document == null)
                {
                    return;
                }
                if (HtmlRenderer.Document.Body != null)
                {
                    HtmlRenderer.Document.Body.KeyDown += Body_KeyDown;
                }
                HtmlRenderer.Document.ContextMenuShowing += Document_ContextMenuShowing;
            }
            catch (Exception ex)
            {
                MessageDialog.Show
                    (
                        "htmlRenderer Exception  \r\n" + ex.InnerException,
                        "Error",
                        MessageDialog.MessageBoxButtons.Ok,
                        MessageDialog.MessageBoxIcon.Error,
                        "" + "\r\n" + ex.StackTrace);
            }
        }
예제 #18
0
 public void Initialize(ISpellingChecker spellingChecker, MshtmlControl mshtmlControl,
     IHTMLDocument2 htmlDocument, ReplaceWord replaceWordFunction, MarkupRangeFilter filter, DamageFunction damageFunction)
 {
     _spellingChecker = spellingChecker;
     _mshtmlControl = mshtmlControl;
     _htmlDocument = htmlDocument;
     _filter = filter;
     _replaceWordFunction = replaceWordFunction;
     _damageFunction = damageFunction;
 }
예제 #19
0
        // document를 일반적으로 가져올 수 없는 경우 (security issue) 이렇게 가져옴.
        public static IHTMLDocument2[] GetHtmlDocumentsByOle(IHTMLDocument2 doc)
        {
            try
            {
                ExceptionTester.Instance.Throw("gethtmlbyole");

                List<IHTMLDocument2> docs = new List<IHTMLDocument2>();

                // add main doc
                docs.Add(doc);

                //get the OLE container from the window's parent
                IOleContainer oc = doc as IOleContainer;      //OC ALLOC

                //get the OLE enumerator for the embedded objects
                int hr = 0;
                IEnumUnknown eu;
                hr = oc.EnumObjects(tagOLECONTF.OLECONTF_EMBEDDINGS, out eu); //EU ALLOC

                Guid IID_IWebBrowser2 = typeof(SHDocVw.IWebBrowser2).GUID;
                object pUnk = null;
                int fetched = 0;
                const int MAX_FETCH_COUNT = 1;

                for (int i = 0; eu.Next(MAX_FETCH_COUNT, out pUnk, out fetched) == hr; i++)
                {
                    //QI pUnk for the IWebBrowser2 interface
                    SHDocVw.IWebBrowser2 brow = pUnk as SHDocVw.IWebBrowser2;

                    if (brow != null)
                    {
                        IHTMLDocument2 d = brow.Document as IHTMLDocument2;
                        //	Logger.Log("wb found. doc's url: {0}", d.url);

                        // if we found document, repeat recursively
                        IHTMLDocument2[] docs2 = GetHtmlDocumentsByOle(d);

                        foreach (IHTMLDocument2 doc2 in docs2)
                        {
                            docs.Add(doc2);
                        }
                    }
                }

                Marshal.ReleaseComObject(eu);                                 //EU FREE

                return docs.ToArray();
            }
            catch (Exception e)
            {
                Logger.Warn("cannt get html doc by ole! {0}", e.Message);

                return new IHTMLDocument2[] { };
            }
        }
예제 #20
0
 protected virtual bool DocumentReadyStateIsAvailable(IHTMLDocument2 document)
 {
     // Sometimes an OutOfMemoryException or ComException occurs while accessing
     // the readystate property of IHTMLDocument2. Giving MSHTML some time
     // to do further processing seems to solve this problem.
     return UtilityClass.TryFuncIgnoreException(() =>
     {
         var readyState = document.readyState;
         return true;
     });
 }
예제 #21
0
 public static bool IsDocumentEqual(IHTMLDocument2 doc1, IHTMLDocument2 doc2)
 {
     try
     {
         return Marshal.GetIUnknownForObject(doc1) == Marshal.GetIUnknownForObject(doc2);
     }
     catch
     {
         return false;
     }
 }
예제 #22
0
 public static bool IsDocumentValid(IHTMLDocument2 doc)
 {
     try
     {
         return !String.IsNullOrEmpty(doc.url) && String.Compare(doc.url, TestConstants.IE_BlankPage_Url, true) != 0;
     }
     catch
     {
         return false;
     }
 }
예제 #23
0
    public DocumentAdapter( object document )
    {
      //_documentUri = documentUri;

      _raw = document;

      _document = document as IHTMLDocument;
      _document2 = document as IHTMLDocument2;
      _document3 = document as IHTMLDocument3;
      _document4 = document as IHTMLDocument4;
      _document5 = document as IHTMLDocument5;
    }
예제 #24
0
        /// <summary>
        /// Aggregates the filter applying process
        /// </summary>
        /// <param name="doc"></param>
        public static void ApplyFilter(ref IHTMLDocument2 doc)
        {
            //Create the specific content-filters
            IHTMLFilter[] filters = new IHTMLFilter[]{
                FilterFactory.CreateFilter(FilterType.FormFilter),
                FilterFactory.CreateFilter(FilterType.ScriptSyndication) };

            foreach (IHTMLFilter filter in filters)
            {
                filter.Filter(ref doc);
            }
        }
예제 #25
0
		/// <summary>
		/// This embeds an inline css stylesheet that allows tags
		/// in the users guide html that are in the class "hideonline"
		/// to be hidden in the version poseted to the website
		/// </summary>
		/// <param name="htmlDoc"></param>
		private static void AddEmbeddedCSS( IHTMLDocument2 htmlDoc )
		{
			IHTMLStyleElement style = htmlDoc.createElement( "style" ) as IHTMLStyleElement;
			style.type = "text/css";
			style.styleSheet.cssText = ".hideonline{ display:none; }";

			IHTMLElementCollection collection = htmlDoc.all.tags( "head" ) as IHTMLElementCollection;
			Debug.Assert( collection != null );
			Debug.Assert( collection.length == 1 );

			mshtml.IHTMLDOMNode head = collection.item( 0, 0 ) as IHTMLDOMNode;
			Debug.Assert( head != null );
			head.appendChild( style as IHTMLDOMNode );
		}
예제 #26
0
        public static bool IsDocumentStateReady(IHTMLDocument2 doc)
        {
            if (doc != null)
            {
                try
                {
                    return doc.readyState == "complete" || doc.readyState == "interactive";
                }
                catch
                {
                }
            }

            return false;
        }
예제 #27
0
        public ImageRakerForm(Toolbar toolbar, IHTMLDocument2 rootDoc, bool instantMode)
        {
            InitializeComponent();

            #if DEBUG
            this.Text = "ImageRaker DEBUG";
            #endif

            thumbnailListView.ListViewItemSorter = comparer;

            this.toolbar = toolbar;
            this.rootDoc = rootDoc;
            this.isThumbnailListViewUpdatable = false;
            this.instantMode = instantMode;
            this.saveCount = 0;
        }
예제 #28
0
        public FreeTextEditor()
        {
            InitializeComponent();

            webBrowser1.DocumentText = "<html><body></body></html>";
            doc =webBrowser1.Document.DomDocument as IHTMLDocument2;
            doc.designMode = "On";

            //将默认的webBrowser的右键菜单替换掉
            webBrowser1.Document.ContextMenuShowing +=
               new HtmlElementEventHandler(Document_ContextMenuShowing);

            InitializeFont();

            timer1.Start();
        }
        /// <summary>
        /// Helper Method to get the IHTMLDocument2
        /// </summary>
        /// <param name="mainWindow"></param>
        /// <returns></returns>
        private static IHTMLDocument2 getHTMLDocument(WindowDetails mainWindow)
        {
            WindowDetails ieServer;

            if ("Internet Explorer_Server".Equals(mainWindow.ClassName))
            {
                ieServer = mainWindow;
            }
            else
            {
                ieServer = mainWindow.GetChild("Internet Explorer_Server");
            }
            if (ieServer == null)
            {
                LOG.WarnFormat("No Internet Explorer_Server for {0}", mainWindow.Text);
                return(null);
            }

            IHTMLDocument2 document2     = null;
            uint           windowMessage = User32.RegisterWindowMessage("WM_HTML_GETOBJECT");

            if (windowMessage == 0)
            {
                LOG.WarnFormat("Couldn't register WM_HTML_GETOBJECT");
                return(null);
            }

            LOG.DebugFormat("Trying WM_HTML_GETOBJECT on {0}", ieServer.ClassName);
            UIntPtr response;

            User32.SendMessageTimeout(ieServer.Handle, windowMessage, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 5000, out response);
            if (response != UIntPtr.Zero)
            {
                document2 = (IHTMLDocument2)Accessible.ObjectFromLresult(response, typeof(IHTMLDocument).GUID, IntPtr.Zero);
                if (document2 == null)
                {
                    LOG.Error("No IHTMLDocument2 found");
                    return(null);
                }
            }
            else
            {
                LOG.Error("No answer on WM_HTML_GETOBJECT.");
                return(null);
            }
            return(document2);
        }
예제 #30
0
        private void LoadPage(string url)
        {
            try
            {
                progressBar1.Visible = true;

                if (Navigate(url) != true)
                {
                    throw (new Exception("Не корректный url."));
                }

                while (Web.ReadyState != WebBrowserReadyState.Complete || Web.IsBusy)
                {
                    //|| Web.Url.AbsoluteUri != url)
                    Application.DoEvents();
                }

                if (Web.Document == null)
                {
                    throw new Exception("Страница не загрузилась.");
                }

                IHTMLDocument2 currentDoc = (IHTMLDocument2)Web.Document.DomDocument;
                if (currentDoc.url.StartsWith("res://"))
                {
                    throw new Exception("Не найдена страница: " + url + "\n");
                }

                if (Web.Document.Body == null)
                {
                    throw new Exception("Документ не заргружен.");
                }

                //progressBar1.Visible = false;
            }
            catch (Exception err)
            {
                progressBar1.Visible = false;
                MessageBox.Show("Произошла ошибка во время работы программы: \n\n" +
                                err.Message, "Ошибка",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                progressBar1.Visible = false;
            }
        }
예제 #31
0
        /// <summary>
        /// 打印文档页面处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintPage(object sender, PrintPageEventArgs e)
        {
            //触发打印页面开始事件
            if (BeforeRendering != null)
            {
                BeforeRendering(this, new PrintArgs("开始渲染"));
            }

            //获取打印句柄
            IntPtr ptr = e.Graphics.GetHdc();

            //重置浏览器窗口大小与打印内容一致
            ResizeWebBrowser();
            //获取Dom对象
            IHTMLDocument2 document = (IHTMLDocument2)this.WebBrowser.Document.DomDocument;

            if (document != null)
            {
                //获取Dom中的Body元素
                IHTMLElement bodyElement = document.body;
                if (bodyElement != null)
                {
                    IHTMLElementRender renderObject = (IHTMLElementRender)bodyElement;

                    //设置打印机并打印
                    renderObject.SetDocumentPrinter(PrintDocument.DefaultPageSettings.PrinterSettings.PrinterName, ptr);
                    renderObject.DrawToDC(ptr);

                    //触发本页打印结束事件
                    if (AfterRendering != null)
                    {
                        AfterRendering(this, new PrintArgs("结束渲染"));
                    }
                }
                else if (RenderMissing != null)
                {
                    RenderMissing(this, new PrintArgs("因bodyElement==null未被渲染"));
                }
            }
            else if (RenderMissing != null)
            {
                RenderMissing(this, new PrintArgs("因document==null未被渲染"));
            }

            //没有后继页面
            e.HasMorePages = false;
        }
        public KeepSourceFormatting(MarkupRange sourceRange, MarkupRange destinationRange)
        {
            Debug.Assert(sourceRange.Start.Container.GetOwningDoc() == destinationRange.Start.Container.GetOwningDoc(),
                "Ranges must share an owning document!");

            if (sourceRange == null)
            {
                throw new ArgumentNullException("sourceRange");
            }

            if (!sourceRange.Positioned)
            {
                throw new ArgumentException("sourceRange must be positioned.");
            }

            if (sourceRange.Start.IsRightOf(sourceRange.End))
            {
                throw new ArgumentException("sourceRange start must be before range end.");
            }

            if (destinationRange == null)
            {
                throw new ArgumentNullException("destinationRange");
            }

            if (!destinationRange.Positioned)
            {
                throw new ArgumentException("destinationRange must be positioned.");
            }

            if (destinationRange.Start.IsRightOf(destinationRange.End))
            {
                throw new ArgumentException("destinationRange start must be before range end.");
            }

            this.sourceDocument = sourceRange.Start.Container.Document;
            this.sourceMarkupServices = new MshtmlMarkupServices((IMarkupServicesRaw)this.sourceDocument);
            this.sourceRange = sourceRange.Clone();
            this.sourceRange.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left;
            this.sourceRange.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;

            this.destinationDocument = destinationRange.Start.Container.Document;
            this.destinationMarkupServices = new MshtmlMarkupServices((IMarkupServicesRaw)this.destinationDocument);
            this.destinationRange = destinationRange.Clone();
            this.destinationRange.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left;
            this.destinationRange.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
        }
예제 #33
0
        //空间动态里的好友
        private void getFriend()
        {
            try
            {
                string info = "";

                mshtml.HTMLDocumentClass htmlDoc = webBrowser1.Document.DomDocument as mshtml.HTMLDocumentClass;

                for (int i = 0; i < htmlDoc.frames.length; ++i)
                {
                    object index = i;
                    mshtml.IHTMLWindow2 frameWindow = htmlDoc.frames.item(ref index) as mshtml.IHTMLWindow2;

                    IHTMLDocument2 frame = CodecentrixSample.CrossFrameIE.GetDocumentFromWindow(frameWindow);

                    for (int j = 0; j < frame.frames.length; ++j)
                    {
                        object rj = j;
                        mshtml.IHTMLWindow2 frameWindow2 = frame.frames.item(ref rj) as mshtml.IHTMLWindow2;

                        IHTMLDocument2 frame2 = CodecentrixSample.CrossFrameIE.GetDocumentFromWindow(frameWindow2);
                        mshtml.IHTMLElementCollection userlist = (mshtml.IHTMLElementCollection)frame2.all.tags("div");
                        IEnumerator users = userlist.GetEnumerator();
                        while (users.MoveNext())
                        {
                            mshtml.IHTMLElement element = (mshtml.IHTMLElement)users.Current;
                            if (element.className == "user-list" || element.className == "ui-avatar")
                            {
                                mshtml.IHTMLElementCollection childrenCol = (mshtml.IHTMLElementCollection)element.children;
                                IEnumerator cusers = childrenCol.GetEnumerator();
                                while (cusers.MoveNext())
                                {
                                    mshtml.IHTMLElement celement = (mshtml.IHTMLElement)cusers.Current;
                                    string href = (string)celement.getAttribute("href", 0);
                                    if (href.Contains("http:"))
                                    {
                                        info += href + "\n";
                                        spider.AddQQ(href);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception) { }
        }
        private void GetInfo()
        {
            IHTMLDocument2 hdoc = doc.DomDocument as IHTMLDocument2;
            IHTMLWindow2   win  = hdoc.parentWindow as mshtml.IHTMLWindow2;
            var            d    = win.execScript(@"function sucdd(){ return popUpWinQm;}", "javascript");

            if (hdoc == null)
            {
                MessageBox.Show("hdoc is null");
            }
            if (win == null)
            {
                MessageBox.Show("win is null");
            }
            HTMLWindow2Class            dddd1    = doc.InvokeScript("sucdd") as HTMLWindow2Class;
            IHTMLWindow2                dddd     = doc.InvokeScript("sucdd") as IHTMLWindow2;
            IHTMLDocument2              popupdoc = dddd.document;
            IHTMLElementCollection      elelist  = popupdoc.all.tags("tr") as IHTMLElementCollection;
            Dictionary <string, string> dic      = new Dictionary <string, string>();
            int i = 0;//申请号,申请人类型(法人或其他组织,自然人),书式类型(中国大陆),申请人名称,身份证明文件号码

            foreach (IHTMLElement item in elelist)
            {
                if (i < 3)
                {
                    continue;
                }
                if (i >= elelist.length - 15)
                {
                    break;
                }
                dic.Add(((item.children as IHTMLElementCollection).item(null, 0) as IHTMLElement).innerText, ((item.children as IHTMLElementCollection).item(null, 1) as IHTMLElement).innerText);
            }
            if (dic.Values.Contains("中国大陆"))
            {
                string regNum            = "";
                string applicantCategory = "";
                string applicant         = "";
                string idCard            = "";
                dic.TryGetValue("申请号", out regNum);
                dic.TryGetValue("申请人类型", out applicantCategory);
                dic.TryGetValue("申请人名称", out applicant);
                dic.TryGetValue("身份证明文件号码", out idCard);
                CommonLibrary.CommonTool.GetResult(currentUrl + string.Format("api/AutoReport/GetAddApplicantRegNum?regNum={0}&category={1}&applicant={2}&idCard={3}&id={4}", regNum, applicantCategory, applicant, idCard, currentId));
            }
            dddd.close();
        }
예제 #35
0
        public void Capture(IHTMLDocument2 doc)
        {
            Bitmap bitmap = new Bitmap(1000, 1000);

            Rectangle imgRectangle = new Rectangle(0, 0, 1000, 1000);

            Rectangle docRect = new Rectangle(0, 0, 1000, 1000);

            IViewObject ivo = doc as IViewObject;

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                IntPtr hdc = g.GetHdc();

                //ivo.Draw(1, -1, IntPtr.Zero, IntPtr.Zero,IntPtr.Zero, hdc, ref Rectangle imgRectangle,ref Rectangle docRect, IntPtr.Zero, 0);
            }
        }
예제 #36
0
        protected virtual bool IsDocumentReadyStateAvailable(IHTMLDocument2 document)
        {
            if (document != null)
            {
                // Sometimes an OutOfMemoryException or ComException occurs while accessing
                // the readystate property of IHTMLDocument2. Giving MSHTML some time
                // to do further processing seems to solve this problem.
                try
                {
                    string readyState = document.readyState;
                    return(true);
                }
                catch {}
            }

            return(false);
        }
예제 #37
0
        public NoteEditor()
        {
            InitializeComponent();

            // setting up WebBrowser for editing
            this.DocumentText  = "<html><body></body></html>";
            htmlDoc            = this.Document.DomDocument as IHTMLDocument2;
            htmlDoc.designMode = "On";

            ScriptErrorsSuppressed         = true;
            IsWebBrowserContextMenuEnabled = false;

            // events
            this.Navigated  += new WebBrowserNavigatedEventHandler(this_Navigated);
            this.Navigating += NoteEditor_Navigating;
            this.GotFocus   += new EventHandler(this_GotFocus);
        }
예제 #38
0
        public static IHTMLElement FindSubmitControlByValueText(IHTMLDocument2 oDoc2, string valueMatch)
        {
            IHTMLElementCollection ihec = oDoc2.all.tags("input");

            foreach (IHTMLElement ihe in ihec)
            {
                IHTMLInputElement iheInput = ihe as IHTMLInputElement;

                if (string.Compare(iheInput.type, "submit", true) == 0)
                {
                    if (valueMatch == null || string.Compare(iheInput.value, valueMatch, true) == 0)
                        return ihe;
                }
            }

            return null;
        }
예제 #39
0
        private void ReadBtn_Click(object sender, EventArgs e)
        {
            IHTMLDocument2       htmlDocument     = webBrowser1.Document.DomDocument as IHTMLDocument2;
            IHTMLSelectionObject currentSelection = htmlDocument.selection;
            IHTMLTxtRange        range            = currentSelection.createRange() as IHTMLTxtRange;

            if (currentSelection != null)
            {
                if (range != null)
                {
                    ConvertedText.Text = range.text;
                }
            }
            ReadBtn.Enabled  = false;
            PauseBtn.Enabled = true;
            s.SpeakAsync(ConvertedText.Text);
        }
예제 #40
0
        private HTMLDocument ReadHtmlDocument(string fileName)
        {
            HTMLDocument htmlDoc = null;

            using (StreamReader reader = new StreamReader(fileName, UTF8Encoding))
            {
                string html = reader.ReadToEnd();

                htmlDoc = new HTMLDocument();

                IHTMLDocument2 docToWritein = htmlDoc as IHTMLDocument2;

                docToWritein.write(new object[] { html });
            }

            return(htmlDoc);
        }
예제 #41
0
        /// <summary>
        /// Downloads a webpage from a blog.
        /// </summary>
        /// <param name="blogHomepageUrl"></param>
        /// <param name="progress"></param>
        /// <returns></returns>
        private Stream DownloadBlogPage(string blogHomepageUrl, IProgressHost progress)
        {
            ProgressTick   tick      = new ProgressTick(progress, 50, 100);
            MemoryStream   memStream = new MemoryStream();
            IHTMLDocument2 doc2      = null;

            // WinLive 221984: Theme detection timing out intermitantly on WordPress.com
            // The temp post *often* takes more than a minute to show up on the blog home page.
            // The download progress dialog has a cancel button, we'll try a lot before giving up.
            for (int i = 0; i < 30 && doc2 == null; i++)
            {
                if (progress.CancelRequested)
                {
                    throw new OperationCancelledException();
                }
                tick.UpdateProgress(0, 0, Res.Get(StringId.ProgressDownloadingWeblogEditingStyle));
                // Sleep to give the post enough time to show up.
                // We'll make 10 attempts with a 1 second delay.
                // Subsequent attempts will use a 10 second delay.
                // This means we'll try for 5 minutes (10s + 290s = 300s) before we consider the operation timed out.
                Thread.Sleep(i < 10 ? 1000 : 10000);


                HttpWebResponse resp = _pageDownloader(blogHomepageUrl, 60000);
                memStream = new MemoryStream();
                using (Stream respStream = resp.GetResponseStream())
                    StreamHelper.Transfer(respStream, memStream);

                //read in the HTML file and determine if it contains the title element
                memStream.Seek(0, SeekOrigin.Begin);
                doc2 = HTMLDocumentHelper.GetHTMLDocumentFromStream(memStream, blogHomepageUrl);
                if (HTMLDocumentHelper.FindElementContainingText(doc2, TEMPORARY_POST_TITLE_GUID) == null)
                {
                    doc2 = null;
                }
            }
            if (doc2 == null)
            {
                throw new OperationTimedOutException();
            }
            tick.UpdateProgress(100, 100);

            //return the stream
            memStream.Seek(0, SeekOrigin.Begin);
            return(memStream);
        }
예제 #42
0
파일: QuestionForm.cs 프로젝트: titu84/Exam
        private void btnTranslate_Click(object sender, EventArgs e)
        {
            string               textToTranslate  = "";
            IHTMLDocument2       htmlDocument     = webBrowser1.Document.DomDocument as IHTMLDocument2;
            IHTMLSelectionObject currentSelection = htmlDocument.selection;

            if (currentSelection != null)
            {
                IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
                if (range != null)
                {
                    textToTranslate = range.text;
                }
            }
            try
            {
                if (String.IsNullOrEmpty(textToTranslate))
                {
                    textToTranslate = getInput(textToTranslate, htmlDocument);
                }
                System.Diagnostics.Process.Start(String.Format("https://translate.google.pl/#view=home&op=translate&sl=en&tl=pl&text={0}", replace(textToTranslate)));
            }
            catch (WebException exc)
            {
                MessageBox.Show("Brak połączenia z internetem lub antywirus blokuje połączenie, próba w otwarcia przeglądarce. \n" + exc.Message, "Błąd!");
                try
                {
                    if (String.IsNullOrEmpty(textToTranslate))
                    {
                        textToTranslate = htmlDocument.body.innerText;
                    }
                    System.Diagnostics.Process.Start(String.Format("https://translate.google.pl/#view=home&op=translate&sl=en&tl=pl&text={0}", replace(textToTranslate)));
                }
                catch (WebException)
                {
                    MessageBox.Show("Brak połączenia z internetem? Brak połączenia z ...www.google.com/translate...", "Błąd!");
                    return;
                }
                return;
            }
            catch (Exception exc)
            {
                MessageBox.Show("Problem z tłumaczeniem.", "Nieznany błąd!");
                return;
            }
        }
예제 #43
0
        private String GetContent(String Rstring)
        {
            String         sString = "";
            HTMLDocument   d       = new HTMLDocument();
            IHTMLDocument2 doc     = (IHTMLDocument2)d;

            doc.write(Rstring);

            IHTMLElementCollection L = doc.links;

            foreach (IHTMLElement links in L)
            {
                sString += links.getAttribute("href", 0);
                sString += "/n";
            }
            return(sString);
        }
예제 #44
0
        public static IHTMLElement FindSubmitControlByName(IHTMLDocument2 oDoc2, string name)
        {
            IHTMLElementCollection ihec = oDoc2.all.tags("input");

            foreach (IHTMLElement ihe in ihec)
            {
                IHTMLInputElement iheInput = ihe as IHTMLInputElement;

                if (string.Compare(iheInput.type, "submit", true) == 0)
                {
                    if (string.Compare(iheInput.name, name, true) == 0)
                        return ihe;
                }
            }

            return null;
        }
 // Returns null in case of failure.
 public static IHTMLDocument2 GetDocumentFromWindow(IHTMLWindow2 htmlWindow)
 {
     if (htmlWindow == null)
     {
         return(null);
     }
     // First try the usual way to get the document.
     try
     {
         IHTMLDocument2 doc = htmlWindow.document;
         return(doc);
     }
     catch (COMException comEx)
     {
         // I think COMException won't be ever fired but just to be sure ...
         if (comEx.ErrorCode != E_ACCESSDENIED)
         {
             return(null);
         }
     }
     catch (System.UnauthorizedAccessException)
     {
     }
     catch
     {
         // Any other error.
         return(null);
     }
     // At this point the error was E_ACCESSDENIED because the frame contains a document from another domain.
     // IE tries to prevent a cross frame scripting security issue.
     try
     {
         // Convert IHTMLWindow2 to IWebBrowser2 using IServiceProvider.
         IServiceProvider sp = (IServiceProvider)htmlWindow;
         // 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);
         return((IHTMLDocument2)browser.Document);
     }
     catch
     {
     }
     return(null);
 }
예제 #46
0
        public void Capture(IHTMLDocument2 doc)
        {
            Bitmap bitmap = new Bitmap(1000, 1000);

            Rectangle imgRectangle = new Rectangle(0, 0, 1000, 1000);

            Rectangle docRect = new Rectangle(0, 0, 1000, 1000);

            IViewObject ivo = doc as IViewObject;

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                IntPtr hdc = g.GetHdc();

                //ivo.Draw(1, -1, IntPtr.Zero, IntPtr.Zero,IntPtr.Zero, hdc, ref Rectangle imgRectangle,ref Rectangle docRect, IntPtr.Zero, 0);
            }
        }
예제 #47
0
    public void DoCapture()
    {
        IHTMLDocument2 doc2  = (IHTMLDocument2)mWb.Document;
        IHTMLDocument3 doc3  = (IHTMLDocument3)mWb.Document;
        IHTMLElement2  body2 = (IHTMLElement2)doc2.body;
        IHTMLElement2  root2 = (IHTMLElement2)doc3.documentElement;

        // Determine dimensions for the image; we could add minWidth here
        // to ensure that we get closer to the minimal width (the width
        // computed might be a few pixels less than what we want).
        int width  = Math.Max(body2.scrollWidth, root2.scrollWidth);
        int height = Math.Max(root2.scrollHeight, body2.scrollHeight);

        // Resize the web browser control
        mWb.SetBounds(0, 0, width, height);

        // Do it a second time; in some cases the initial values are
        // off by quite a lot, for as yet unknown reasons. We could
        // also do this in a loop until the values stop changing with
        // some additional terminating condition like n attempts.
        width  = Math.Max(body2.scrollWidth, root2.scrollWidth);
        height = Math.Max(root2.scrollHeight, body2.scrollHeight);
        mWb.SetBounds(0, 0, width, height);

        Bitmap   image = new Bitmap(width, height);
        Graphics g     = Graphics.FromImage(image);

        _RECTL bounds;

        bounds.left   = 0;
        bounds.top    = 0;
        bounds.right  = width;
        bounds.bottom = height;

        IntPtr      hdc = g.GetHdc();
        IViewObject iv  = doc2 as IViewObject;

        // TODO: Write to Metafile instead if requested.

        iv.Draw(1, -1, (IntPtr)0, (IntPtr)0, (IntPtr)0,
                (IntPtr)hdc, ref bounds, (IntPtr)0, (IntPtr)0, 0);

        g.ReleaseHdc(hdc);
        image.Save(mFile);
        image.Dispose();
    }
예제 #48
0
 /// <include file='doc\StyleBuilderForm.uex' path='docs/doc[@for="StyleBuilderForm.InitPreview"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 protected void InitPreview()
 {
     // create the Trident instance
     if (mshtmlControl.CreateTrident())
     {
         // create the preview
         IHTMLDocument2 document = mshtmlControl.GetDocument();
         if (document != null)
         {
             preview = new StyleBuilderPreview(document);
             if (preview.InitPreview(context.GetUrl()) == false)
             {
                 preview = null;
             }
         }
     }
 }
예제 #49
0
        private IHTMLDocument2 WaitWhileFrameDocumentNotAvailable(IWebBrowser2 frame)
        {
            IHTMLDocument2 document = null;

            while (document == null)
            {
                try
                {
                    document = frame.Document as IHTMLDocument2;
                }
                catch { }

                document = IsDocumentAvailable(document, "frame");
            }

            return(document);
        }
예제 #50
0
        public MathDialogBox(IHTMLDocument2 mainWindowDoc, string imagePath)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Settings.Default.ProgramLanguage.ToString());
            InitializeComponent();

            doc = mainWindowDoc;

            host.Dock  = DockStyle.Fill;
            host.Child = formula;

            System.Windows.Media.Brush br = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255));
            formula.BorderBrush     = br;
            formula.BorderThickness = new Thickness(3, 3, 3, 3);

            imageFolderPath         = imagePath;
            noneRadioButton.Checked = true;
        }
예제 #51
0
        private IHTMLDocument2 GetSafeHTMLDocument2()
        {
            IHTMLDocument2 doc = null;

            try
            {
                ExceptionTester.Instance.Throw("openimagerakerform");

                doc = webBrowserClass.Document as IHTMLDocument2;
            }
            catch (Exception e)
            {
                Logger.Warn("exception on getting HTMLDocument {0}", e.Message);
            }

            return(doc);
        }
예제 #52
0
        public Document(string name)
        {
            page          = new TabPage("Untitled");
            viewTabs      = new TabControl();
            viewTabs.Dock = DockStyle.Fill;
            page.Click   += new EventHandler(page_Click);

            wysiwyg   = new TabPage("WYSIWYG");
            html      = new WebBrowser();
            html.Dock = DockStyle.Fill;
            wysiwyg.Controls.Add(html);
            viewTabs.TabPages.Add(wysiwyg);

            // Configure browser
            html.AllowNavigation                = false;
            html.AllowWebBrowserDrop            = false;
            html.IsWebBrowserContextMenuEnabled = false;
            html.ScriptErrorsSuppressed         = true;
            html.DocumentText = "<html><body></body></html>";
            doc            = html.Document.DomDocument as IHTMLDocument2;
            doc.designMode = "On";

            codeView       = new TabPage("Markdown");
            code           = new TextBox();
            code.Dock      = DockStyle.Fill;
            code.Multiline = true;
            codeView.Controls.Add(code);
            viewTabs.TabPages.Add(codeView);
            code.Font       = new System.Drawing.Font("Courier New", 10);
            code.ScrollBars = ScrollBars.Vertical;

            htmlView           = new TabPage("HTML");
            htmlCode           = new TextBox();
            htmlCode.Dock      = DockStyle.Fill;
            htmlCode.Multiline = true;
            htmlView.Controls.Add(htmlCode);
            viewTabs.TabPages.Add(htmlView);
            htmlCode.Font       = new System.Drawing.Font("Courier New", 10);
            htmlCode.ScrollBars = ScrollBars.Vertical;

            page.Controls.Add(viewTabs);

            ID = Guid.NewGuid();

            Bold = Italic = Strike = UnorderedList = OrderedList = false;
        }
예제 #53
0
        void Instance_SearchComplete(object sender, SearchEventArgs e)
        {
            StringWriter writer = new StringWriter();

            transform.Transform(e.Result, new XmlTextWriter(writer));
            IHTMLDocument2 doc = (IHTMLDocument2)Explorer.Document;

            doc.clear();
            try
            {
                doc.body.innerHTML = "";
                doc.write(writer.ToString());
            }
            catch
            {
            }
        }
예제 #54
0
        public override BlogPostRegions LocateRegionsOnUIThread(IProgressHost progress)
        {
            blogHomepageContents.Seek(0, SeekOrigin.Begin);
            IHTMLDocument2 doc2 = HTMLDocumentHelper.GetHTMLDocumentFromStream(blogHomepageContents, _blogHomepageUrl);

            // Ensure that the document is fully loaded.
            // If it is not fully loaded, then viewing its current style is non-deterministic.
            DateTime startedDoingEvents = DateTime.Now;

            while (!progress.CancelRequested && !HTMLDocumentHelper.IsReady(doc2))
            {
                if (DateTime.Now.Subtract(startedDoingEvents).TotalMilliseconds > 10000)
                {
                    // Timing out here is not fatal.
                    Trace.WriteLine("Timed out while loading blog homepage for theme detection.");
                    break;
                }

                Application.DoEvents();
            }

            IHTMLElement[] titles = FindText(_titleText, doc2.body);
            IHTMLElement[] bodies = FindText(_bodyText, doc2.body);
            if (titles.Length == 0 || bodies.Length == 0)
            {
                throw new Exception("Unable to locate blog post elements using most recent post");
            }

            if (IsSmartContent(bodies[0]))
            {
                throw new Exception("Most recent post is smart content");
            }

            BlogPostRegions regions = new BlogPostRegions();

            regions.TitleRegions = titles;

            //scrub the post body element to avoid improperly including extraneous parent elements
            regions.BodyRegion = ScrubPostBodyRegionParentElements(bodies[0]);
            regions.Document   = doc2;

            progress.UpdateProgress(100, 100);

            return(regions);
        }
예제 #55
0
        public void ApplyFlashQualityScript(object sender, NavigationEventArgs e)
        {
            try
            {
                var document               = this.WebBrowser.Document as HTMLDocument;
                FramesCollection frames    = document.frames;
                HTMLDocument     mainFrame = null;
                for (int i = 0; i < frames.length; i++)
                {
                    object         refIndex = i;
                    IHTMLDocument2 frame    = CrossFrameIE.GetDocumentFromWindow((IHTMLWindow2)frames.item(ref refIndex));
                    if (frame != null && ((HTMLDocument)frame).getElementById("flashWrap") != null)
                    {
                        mainFrame = (HTMLDocument)frame;
                        break;
                    }
                    else
                    {
                        mainFrame = document;
                    }
                }

                if (mainFrame != null)
                {
                    // Javascript injection - Greasemonkey style. Suppose to be more dynamic on DOM objects.
                    // Main reason for JS method is that the flash itself doesn't exist until after it has been added to the "flashWrap" DIV element!
                    // Leave the timing of when the flash is added to the script.
                    IHTMLElement       head         = (IHTMLElement)((IHTMLElementCollection)mainFrame.all.tags("head")).item(null, 0);
                    IHTMLScriptElement scriptOjbect = (IHTMLScriptElement)mainFrame.createElement("script");
                    scriptOjbect.type = @"text/javascript";
                    scriptOjbect.text = string.Format(Properties.Settings.Default.FlashQualityJS, KCVSettings.Current.FlashQuality, KCVSettings.Current.FlashWindow);
                    ((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptOjbect);
                }

                if (mainFrame == null && document.url.Contains(".swf?"))
                {
                    // No dynamic way of accessing and editing this, so we forcefully make our own embed since its already provided for us.
                    document.body.innerHTML = string.Format(Properties.Settings.Default.FlashEmbed, KCVSettings.Current.FlashQuality, KCVSettings.Current.FlashWindow, document.url);
                }
            }
            catch (Exception ex)
            {
                StatusService.Current.Notify("Failed to apply quality setting: " + ex.Message);
            }
        }
예제 #56
0
        public SHDocVw.InternetExplorer GetIEFromAutomationelement(AutomationElement element) //***************
        {
            IntPtr HWND = (IntPtr)element.Current.NativeWindowHandle;

            int    hInst = 0;
            IntPtr lres  = IntPtr.Zero;

            SHDocVw.InternetExplorer browser = null;
            //System.Windows.Forms.WebBrowser br;
            IHTMLDocument2 htmlDoc = null;

            hInst = LoadLibrary("Oleacc.dll");
            int?addr = GetProcAddress(HWND, "ObjectFromLresult");

            if (addr != null)
            {
                try
                {
                    uint msg = RegisterWindowMessage("WM_HTML_GETOBJECT");
                    SendMessageTimeout(HWND, msg, IntPtr.Zero, IntPtr.Zero, (uint)SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 1000, out lres);
                    ObjectFromLresult((int)lres, ref IID_IHTMLDocument, 0, ref htmlDoc);
                    Object o;

                    ((IServiceProvider)htmlDoc).QueryService(ref
                                                             SID_SWebBrowserApp, ref IID_IWebBrowser, out o);

                    browser = (SHDocVw.InternetExplorer)o;
                    // br = (System.Windows.Forms.WebBrowser)o;
                }
                catch (Exception e)
                {
                    Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {e.Message}");
                }

                finally
                {
                    FreeLibrary(hInst);
                }
                return(browser);
            }
            else
            {
                return(null);
            }
        }
    public string getResultsViaWebClient(string url)
    {
        WebClient client = new WebClient();
        // Retrieve resource as a stream
        Stream data = client.OpenRead(new Uri(url));
        // Retrieve the text
        StreamReader reader      = new StreamReader(data);
        string       htmlContent = reader.ReadToEnd();

        // Cleanup
        data.Close();
        reader.Close();



        // Obtain the document interface
        IHTMLDocument2 htmlDocument = (IHTMLDocument2) new mshtml.HTMLDocument();

        // Construct the document
        htmlDocument.write(htmlContent);

        //  listBox1.Items.Clear();
        List <string> images          = new List <string>();
        List <string> allElementsList = new List <string>();

        // Extract all elements
        IHTMLElementCollection allElements = htmlDocument.all;

        // Iterate all the elements and display tag names
        foreach (IHTMLElement element in allElements)
        {
            allElementsList.Add(element.tagName);
        }

        // Extract all image elements
        IHTMLElementCollection imgElements = htmlDocument.images;

        // Iterate through each image element
        foreach (IHTMLImgElement img in imgElements)
        {
            images.Add(img.src);
        }

        return(htmlContent);
    }
예제 #58
0
        //检测是否已评论
        private mshtml.IHTMLElement gerCommented()
        {
            String myqq = getMyQQ();

            mshtml.HTMLDocumentClass htmlDoc = webBrowser1.Document.DomDocument as mshtml.HTMLDocumentClass;
            for (int i = 0; i < htmlDoc.frames.length; ++i)
            {
                object index = i;
                mshtml.IHTMLWindow2 frameWindow = htmlDoc.frames.item(ref index) as mshtml.IHTMLWindow2;

                IHTMLDocument2 frame = CodecentrixSample.CrossFrameIE.GetDocumentFromWindow(frameWindow);

                mshtml.IHTMLElementCollection tagls = (mshtml.IHTMLElementCollection)frame.all.tags("div");
                IEnumerator tagie = tagls.GetEnumerator();
                while (tagie.MoveNext())
                {
                    mshtml.IHTMLElement element = (mshtml.IHTMLElement)tagie.Current;
                    if (element.className == "mod-comments")
                    {
                        mshtml.IHTMLElementCollection childrenCol = (mshtml.IHTMLElementCollection)element.all;
                        IEnumerator cusers    = childrenCol.GetEnumerator();
                        bool        cangonext = true;
                        while (cusers.MoveNext())
                        {
                            mshtml.IHTMLElement celement = (mshtml.IHTMLElement)cusers.Current;
                            Console.WriteLine(celement.className);
                            if (celement.className == "comments-item bor3")
                            {
                                if ((String)celement.getAttribute("data-uin", 0) == myqq)
                                {
                                    cangonext = false;
                                    break;
                                }
                            }
                        }
                        //1.打开编辑框
                        if (cangonext)//自己没有评论
                        {
                            return(element);
                        }
                    }
                }
            }
            return(null);
        }
예제 #59
0
        // Returns null in case of failure.
        public static IHTMLDocument2 GetDocumentFromWindow(IHTMLWindow2 htmlWindow)
        {
            if (htmlWindow == null)
            {
                return(null);
            }

            // First try the usual way to get the document.
            try
            {
                IHTMLDocument2 doc = htmlWindow.document;
                return(doc);
            }
            catch (COMException comEx)
            {
                // I think COMException won't be ever fired but just to be sure ...
                if (comEx.ErrorCode != E_ACCESSDENIED)
                {
                    return(null);
                }
            }
            catch (System.UnauthorizedAccessException)
            {
            }
            catch
            {
                // Any other error.
                return(null);
            }

            // At this point the error was E_ACCESSDENIED because the frame contains a document from another domain.
            // IE tries to prevent a cross frame scripting security issue.
            try
            {
                // Get the document from IWebBrowser2.
                SHDocVw.IWebBrowser2 browser = GetIWebBrowser2(htmlWindow);

                return((IHTMLDocument2)browser.Document);
            }
            catch
            {
            }

            return(null);
        }
예제 #60
0
        public string Capture(int timeoutMs)
        {
            // flag indicating whether we should continue with the capture
            bool continueCapture = true;

            // request the page
            HttpWebResponse response = RequestPage(TargetUrl, timeoutMs);

            OnHeadersReceived(response.Headers, ref continueCapture);
            if (!continueCapture)
            {
                throw new OperationCancelledException();
            }

            // transfer it to a stream
            MemoryStream pageStream = new MemoryStream();

            using (Stream responseStream = response.GetResponseStream())
                StreamHelper.Transfer(responseStream, pageStream);
            pageStream.Seek(0, SeekOrigin.Begin);

            // allow filter on content
            OnContentReceived(new StreamReader(pageStream).ReadToEnd(), ref continueCapture);
            if (!continueCapture)
            {
                throw new OperationCancelledException();
            }
            pageStream.Seek(0, SeekOrigin.Begin);

            // Read the stream into a lightweight HTML doc. We use from LightWeightHTMLDocument.FromIHTMLDocument2
            // instead of LightWeightHTMLDocument.FromStream because from stream improperly shoves a saveFrom declaration
            // above the docType (bug 289357)
            IHTMLDocument2          doc  = HTMLDocumentHelper.StreamToHTMLDoc(pageStream, TargetUrl, false);
            LightWeightHTMLDocument ldoc = LightWeightHTMLDocument.FromIHTMLDocument2(doc, TargetUrl, true);

            // download references
            FileBasedSiteStorage       siteStorage = new FileBasedSiteStorage(DestinationPath, "index.htm");
            PageToDownload             page        = new PageToDownload(ldoc, TargetUrl, siteStorage.RootFile);
            PageAndReferenceDownloader downloader  = new PageAndReferenceDownloader(new PageToDownload[] { page }, siteStorage);

            downloader.Download(new TimeoutProgressHost(timeoutMs));

            // return path to captured page
            return(Path.Combine(DestinationPath, siteStorage.RootFile));
        }