開發 IE 瀏覽器的 Toolbar
最近有可能需要開發一個,由 client 端瀏覽網頁,並對網頁內容做一些剪貼處理的批次作業。要用哪種 client 技術並無限制,若想用 Adobe AIR 來開發也是可以嘗試看看,不過,我還是先嘗試另一個我可能比較能找到資源的技術,使用 C# 寫 IE Component。
以下這篇文章是一個很好的基礎,這位 Pavel Zolnikov 開發了一個 Band Objects,並提供了一個小小的按鈕範例:
Extending Explorer with Band Objects using .NET and Windows Forms
http://www.codeproject.com/KB/shell/dotnetbandobjects.aspx
這個範例非常基礎(不是意指簡單,而是它是根基),因為我後來發現有不少其他文章都是使用到這個範例,總之有需要的人可以自行下載他的 source code 做修改即可使用。
我要進行的範例是,在 html 畫面中,有兩個 form,各自擁有一個 textarea,每個 html element 我都沒有指定 id 或 name,在 C# 程式中我將用數字 index 來指到對應的元素,html 內容如下:
<html>
<head>
<title>test page</title>
</head>
<body>
<form>
來源資料:<br>
<textarea rows="5" cols="20">測試資料
'單引號
"雙引號</textarea>
</form>
<form>
複製目的:<br>
<textarea rows="5" cols="20"></textarea>
</form>
</body>
</html>
這個測試用的 html 我放在本機電腦的 http://127.0.0.1/temp/test.html 位置。
接著看到 C# 中的程式,首先先看到畫面編排,我準備了三個按鈕。
button1:連到測試網頁
button2:顯示網頁 title
button3:將測試網頁中 form 1 的 textarea 內容,複製到 form 2 的 textarea 中。
畫面如下:

這三個按鈕的 click 程式如下,也是我唯一需要修改或新增的程式:
private void button1_Click(object sender, System.EventArgs e)
{
IWebBrowser2 webBrowser = (IWebBrowser2)this.Explorer;
object Null = System.Reflection.Missing.Value;
webBrowser.Navigate("http://127.0.0.1/temp/test.html", ref Null, ref Null, ref Null, ref Null);
}
private void button2_Click(object sender, System.EventArgs e)
{
IWebBrowser2 webBrowser = (IWebBrowser2)this.Explorer;
IHTMLDocument2 document = (IHTMLDocument2)webBrowser.Document;
MessageBox.Show(document.title);
}
private void button3_Click(object sender, System.EventArgs e)
{
IWebBrowser2 webBrowser = (IWebBrowser2)this.Explorer;
IHTMLDocument2 document = (IHTMLDocument2)webBrowser.Document;
string data = (((document.forms.item(0, 0) as HTMLFormElement).elements as HTMLElementCollection).item(0, 0) as HTMLTextAreaElement).value;
(((document.forms.item(1, 0) as HTMLFormElement).elements as HTMLElementCollection).item(0, 0) as HTMLTextAreaElement).value = data;
}
對於 MSHTML 的物件結構,可以參考 MSDN:
http://msdn.microsoft.com/en-us/library/aa741322%28VS.85%29.aspx
在 visual studio 2003 中 build solution 後,Register 專案會負責將 SampleBars.dll 用 Regasm 註冊完成,重新開啟 IE 瀏覽器後,就可以看到以下畫面,分別按下三個按鈕時的畫面:
button1:連到測試網頁:

button2:顯示網頁 title:

button3:將測試網頁中 form 1 的 textarea 內容,複製到 form 2 的 textarea 中:

有了這個基礎範例後,就可以做一些比較複雜的工作了。
2 意見:
你好,
我最近也做好了一個 toolbar 利用 你提到的 band object 範例修改, 但是遇到一個問題就是..我希望這個toolbar只能在iexplorer 出現, 在一般的explorer永遠被disable掉...但是不知道怎麼處理..想請問您有沒有什麼建議?? 感謝!
P.S. 我已經有使用BHO set NoExplorer=1
讓這個Toolbar可以一開始就在ie出現, 但是不會出現在 explorer 上面, 但是如果在工具列->檢視-> 去選擇他..就還是會跑出來..
除非先有辦法能識別這些 IE 的兒子,在我看來可能是沒有,因為像是一些網站流量統計中判別瀏覽器種類,好像也無法辨識出來的樣子。
張貼意見