4) 應該在程式命名空間聲明之前,包含下面的介面聲明以添加對Microsoft HTML (MSHTML) IOleCommandTarget介面的參照引用:
using System; using System.Runtime.InteropServices;[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] public struct OLECMDTEXT { public uint cmdtextf; public uint cwActual; public uint cwBuf; [MarshalAs(UnmanagedType.ByValTStr,SizeConst=100)]public char rgwz; } [StructLayout(LayoutKind.Sequential)] public struct OLECMD { public uint cmdID; public uint cmdf; } // IOleCommandTarget的Interop定義 [ComImport, Guid("b722bccb-4e68-101b-a2bc-00aa00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IOleCommandTarget { //重要: 下面方法的順序非常重要,因為本樣本中我們使用的是早期繫結,詳見MSDN中有關.net/COM互操作的參考。 void QueryStatus(ref Guid pguidCmdGroup, UInt32 cCmds, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] OLECMD[] prgCmds, ref OLECMDTEXT CmdText); void Exec(ref Guid pguidCmdGroup, uint nCmdId, uint nCmdExecOpt, ref object pvaIn, ref object pvaOut); } |
2、為CGID_IWebBrowser定義一個GUID
必須定義CGI_IWebBrowser的GUID以通知MSHTML如何來處理你的命令ID。在.NET中實現如下:
private Guid cmdGuid = new Guid("ED016940-BD5B-11CF-BA4E-00C04FD70816"); private enum MiscCommandTarget { Find = 1, ViewSource, Options } |
3、調用Exec()方法
注意,下列三個過程成功調用Exec()的前提是,已經存在名為webBrowser的瀏覽器控制項的被包容執行個體。
private mshtml.HTMLDocument GetDocument() { try { mshtml.HTMLDocument htm = (mshtml.HTMLDocument)axWebBrowser2.Document; return htm; } catch { throw (new Exception("不能從WebBrowser控制項中擷取檔案對象")); } }//查看源碼的方法 public void ViewSource() { IOleCommandTarget cmdt; Object o = new object(); try { cmdt = (IOleCommandTarget)GetDocument(); cmdt.Exec(ref cmdGuid, (uint)MiscCommandTarget.ViewSource, (uint)SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref o, ref o); } catch(Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } } public void Find() { IOleCommandTarget cmdt; Object o = new object(); try { cmdt = (IOleCommandTarget)GetDocument(); cmdt.Exec(ref cmdGuid, (uint)MiscCommandTarget.Find, (uint)SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref o, ref o); } catch(Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } } //顯示“選項”對話方塊的方法 public void InternetOptions() { IOleCommandTarget cmdt; Object o = new object(); try { cmdt = (IOleCommandTarget)GetDocument(); cmdt.Exec(ref cmdGuid, (uint)MiscCommandTarget.Options, (uint)SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT, ref o, ref o); } catch { // 注意:因為該過程相應的CMDID是在Internet Explorer處理 // ,所以此處的異常代碼塊將總被啟用,即使該對話方塊及其操作成功。 //當然,你可以通過瀏覽器選擇設定來禁止這種錯誤的出現。 //不過,即使出現這種提示,對你的主機也無任何損害。 } } |
四、總結
本文通過C#編例,詳細介紹如何?一種多頁面瀏覽程式的基本原理。歡迎同仁批評指正。 另外,本文所附來源程式在Windows 2000/.Net 2003/Internet Explorer 6平台上調試通過。