MSHTML ohne WebBrowser als Parser benutzen  
Frank Dzaebel, erstellt am: 13.08.06, zuletzt geändert:  13.08.06
Kategorie: Implementation, .NET-Version: 2.0, [Download]

Es wird gezeigt, wie man ohne WebBrowser-Control die MSHTML-Bibliothek zum Parsen einer HTML-Datei (oder URL) benutzen kann. Hier wird einmal die Text-Darstellung ausgegeben und einmal nur die Links. Es sind aber etliche andere Dinge machbar, da die MSHTML-Bibliothek hier über COM eine Fülle an Funktionen bereitstellt.

- HtmlDocument.Links-Eigenschaft
- HtmlDocument-Member

using System;
using System.ComponentModel;
using System.Windows.Forms;
using mshtml; 
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;

namespace MshtmlParser
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void Form1_Load(object sender,EventArgs e)
    {
      this.Show(); Cursor = Cursors.WaitCursor;
      url = "http://www.selfhtml.de";
      IHTMLDocument2 htdoc = GetHTMLDocument(url);
      Cursor = Cursors.Default;
      MessageBox.Show(htdoc.body.innerText);
      StringBuilder sb = new StringBuilder(""); 
      foreach (object link in htdoc.links)
      {
        HTMLAnchorElement ha = link as HTMLAnchorElement;
        if (ha != null) { sb.AppendLine(ha.href); continue; }
      }
      MessageBox.Show(sb.ToString());
    }

    [ComVisible(true),ComImport(),
    Guid("7FD52380-4E07-101B-AE2D-08002B2EC713"),
    InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IPersistStreamInit
    {
      void GetClassID([In,Out] ref Guid pClassID);
      [return: MarshalAs(UnmanagedType.I4)]
      [PreserveSig] int IsDirty();
      void Load([In,MarshalAs(UnmanagedType.Interface)] UCOMIStream pstm);
      void Save([In,MarshalAs(UnmanagedType.Interface)] UCOMIStream pstm,
        [In, MarshalAs(UnmanagedType.I4)] int fClearDirty);
      void GetSizeMax([Out,MarshalAs(UnmanagedType.LPArray)] long pcbSize);
      void InitNew();
    }

    private IHTMLDocument2 retDoc;
    private string url;

    public IHTMLDocument2 GetHTMLDocument(string url)
    {
      this.url = url;
      ThreadStart st = new ThreadStart(CreateNewDoc);
      Thread LoadPage = new Thread(st);
      LoadPage.Start();  LoadPage.Join();
      while (retDoc.readyState != "complete") ;
      return retDoc;
    }

    private void CreateNewDoc()
    {
      HTMLDocument oDoc = new HTMLDocument();
      IPersistStreamInit ips;
      ips = (IPersistStreamInit)oDoc;
      ips.InitNew();
      retDoc = oDoc.createDocumentFromUrl(url,"");
    }
  }
}