Com interop avec internet explorer (shdocvw, mshtml) en c#

Description

L'utilisation de SHDocVw.dll et MSHTML.tlb pour acquérir des données d'une page web (HTML) affichée par Internet Explorer. Cette librairie contient une methode qui livre le nombre des Explorer (Explorer.exe et IExplore.exe) déjà executés, le contenu HTML de la page, l'adresse URL et le titre affichés par Internet Explorer. Il faut attribuer à la propriété SearchedTitle une valeur qui équivaut à un titre affiché par un Internet Explorer, pour en acquérir les données de cette page web. Cela est possible à l'aide de COM Interoperabilité entre MS.Net (C#) et le système Windows, ici Windows XP.

Source / Exemple :


using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
//First add these references: SHDocVw.dll and mshtml.tlb
using mshtml;
using SHDocVw; // SHDocVw can be replaced by MeoSHDocVw
//MeoSHDocVw.dll is an interop dll for SHDocVW.dll with a strong name key in the file MeoSHDocVw.snk,
//created like this: 
//1) run  sn.exe -k MeoSHDocVw.snk 
//2) After that  run TlbImp.exe c:\windows\system32\ShdocVw.dll /keyfile:MeoSHDocVw.snk /out:MeoSHDocVw.dll 

namespace ClassLibrary1
{
    /// <summary>
    /// Autor: Didier Meo, ICT Consultant, developed for http://www.meo-x.net
    /// </summary>
    public class IExplorer
    {
        #region class variables & Constructor

        //private static SHDocVw.InternetExplorer _Explorer = null;
        private static SHDocVw.IWebBrowserApp _Webbrowser = null;
        private static mshtml.HTMLDocument _objDocument = null;
        private SHDocVw.ShellWindows _ShellWindows = null;
        private int _iIEnr = 0;
        private bool _blnSearchedExplorer = false;
        private string _strSearchedTitle = null;
        private string _strContent = null, _strContentAll = null, _strLocationURL = null, _strTitle = null;
        private int _iFrameNumber = 0;

        /// 
        /// Constructor for IExplorer
        /// 
        public IExplorer()
        {
            this._strSearchedTitle = "";
            this._Init();
        }

        #endregion

        #region Properties

        /// 
        /// Location URL 
        /// 
        public string HttpUrl
        {
            get
            {
                return _strLocationURL;
            }
            set
            {
                _strLocationURL = (string)value.ToString();
            }
        }

        /// 
        /// Searched Title 
        /// 
        public string SearchedTitle
        {
            set
            {
                _strSearchedTitle = (string)value.ToString();
            }
        }

        /// 
        /// Content for a Frame or for a page without Frames
        /// 
        public string Content
        {
            get
            {
                return this._strContent;
            }
        }

        /// 
        /// Content of an HTML page without Frames or Content for all Frames separated by STX 
        /// 
        public string ContentAll
        {
            get
            {
                return this._strContentAll;
            }
        }

        /// 
        /// Title of an HTML page
        /// 
        public string Title
        {
            get
            {
                return this._strTitle;
            }
        }

        /// 
        /// Number of frames for an HTML page
        /// 
        public int FrameNumber
        {
            get
            {
                return this._iFrameNumber;
            }
        }

        #endregion

        #region Methods

        /// 
        /// Initialization of Variables
        /// 
        [ComVisible(false)]
        private void _Init()
        {
            this._strContent = "";
            this._strContentAll = "";
            this._strLocationURL = "";
            this._strTitle = "";
            this._iFrameNumber = 0;
            this._iIEnr = 0;
        }

        /// 
        /// Gett Internet Explorer Data (URL, Title, Content) for a searched HTML page or for all its frames. 
        /// 
        public void GetIExplorerData()
        {
            this._Init();
            this._blnSearchedExplorer = false;
            _ShellWindows = new SHDocVw.ShellWindows();
            _iIEnr = _ShellWindows.Count;
            if (_iIEnr < 1)
            {
                this._blnSearchedExplorer = false;
                return;
            }
            _objDocument = new mshtml.HTMLDocument();
            for (int nI = 0; nI < _iIEnr; nI++)
            {
                object index = (object)nI;
                _strLocationURL = "";
                _strTitle = "";
                object oSWItem = _ShellWindows.Item(index);
                _Webbrowser = (IWebBrowserApp)oSWItem;
                try
                {
                    _objDocument = (mshtml.HTMLDocument)_Webbrowser.Document;
                    _strLocationURL = _Webbrowser.LocationURL;
                    _strTitle = _objDocument.title;
                    if (_strTitle.IndexOf(this._strSearchedTitle) > -1)
                    {
                        this._blnSearchedExplorer = true;
                    }
                }
                catch (System.Exception exc)
                {
                    if (nI >= _iIEnr - 1)
                    {
                        return;
                    }
                }
                //
                if (this._blnSearchedExplorer)
                {
                    this._strContent = "";
                    this._strContentAll = "";
                    mshtml.FramesCollection oFrameCol = _objDocument.frames;
                    this._iFrameNumber = oFrameCol.length;
                    if (_iFrameNumber == 0)
                    {
                        try
                        {
                            this._strContent = _objDocument.body.outerHTML;
                            this._strContentAll = this._strContent;
                        }
                        catch (System.Exception exc)
                        {
                            return;
                        }
                        return;
                    }
                    this._strContent = "";
                    this._strContentAll = "";
                    this._iFrameNumber = 0;
                    IHTMLElementCollection iElcol = _objDocument.getElementsByTagName("frame");
                    foreach (IHTMLElement iEl in iElcol)
                    {
                        HTMLFrameElement frm = (HTMLFrameElement)iEl;
                        DispHTMLDocument doc = (DispHTMLDocument)((SHDocVw.IWebBrowser2)frm).Document;
                        if (_iFrameNumber > 0) this._strContentAll += Convert.ToChar(2); //STX (start of text) = ASCII CHAR(2) 
                        this._strContent = doc.body.outerHTML;
                        this._strContentAll += this._strContent;
                        _iFrameNumber++;
                    }
                    return;
                }
                else
                {
                    this._strContent = "";
                    this._strContentAll = "";
                    _iFrameNumber = -1;
                    _strLocationURL = "";
                    _strTitle = "";
                }
            }
        }

        #endregion

    }
}

Conclusion :


Après la compilation on obtient un fichier dll. On peut continuer le développement de cette source pour acquérir toutes les donées du contenu HTML de la page web.

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.