自己做瀏覽器?有沒有搞錯?不要說像IE這樣的龐然大物,就是小巧的Opera,我們大多數普通人也決計搞不出來。但如果你的機器裡裝有VB5.0專業版,那麼事情就好辦多了,想試試看嗎?那好,Let`s go!
程式的主角是一個ActiveX控制項:WebBrowser。當然,預設狀態下VB的工具箱中並沒有它,我們得手工加入,方法是:右鍵單擊工具箱,在出現的快捷選單中選擇“部件...”,確保在彈出的對話框中選中「控制項」標籤,找到Microsoft Internet Controls,在它前面的小方塊中打鉤,然後確定。此時你會發現工具箱中多了兩個小圖標,其中,地球圖標代表的控制項正是我們需要的WebBrowser。
由於許多人對WebBrowser控制不是很熟悉,VB的幫助中也沒有有關它的內容(反正我沒有找到),因此有必要介紹一下它的屬性、方法和事件,限於篇幅,我們只涉及程式中用到的:
屬性:LocationURL 傳回控制項顯示WEB頁面的URL。
方法:Navigate 轉移到指定的URL或開啟指定HTML檔案。
事件:1. DownloadBegin 下載操作開啟時觸發。
2. DownloadComplete 下載操作完成、終止或失敗時觸發。
3. ProgressChange WebBrowser控制項追蹤下載操作的過程,並定期觸發此事件。其文法為:Sub WebBrowser_ProgressChange (ByVal Progress As Long, ByVal ProgressMax As Long)。 Progress變元是目前已下載的資料總量,ProgressMax變元是將要下載的資料總量。
4. TitleChange 當目前文件標題改變時觸發
除了WebBrowser控制之外,程式還需要一個Label控制:Label1;一個ComboBox控制項:combo1,用來顯示URL位址;一個StatusBar控制項:StatusBar1;一個ProgressBar控制:ProgressBar1,用來顯示下載進度(StatusBar控制和ProgressBar控制項是ActiveX控制項Microsoft Windows Common Controls5.0的成員,加入工具箱的方法同WebBrowser控制項),這些控制項的屬性值都用預設值。
以下是程序清單:
Option Explicit Private Sub Form_Load() Me.Caption ="My Explorer" Label1.Caption = "URL" Combo1.Text = "" Combo1.Top = Label1.Height Combo1.Left = 0 WebBrowser1.Top = Combo1.Top + Combo1.Height WebBrowser1.Left = 0 Form_Resize StatusBar1.Style = sbrSimple ProgressBar1.Zorder End Sub |
Private Sub Form_Resize() On Error GoTo a Combo1.Width = Form1.Width - 100 WebBrowser1.Width = Combo1.Width WebBrowser1.Height = Form1.Height - Combo1.Height - 1000 ProgressBar1.Top = Me.Height - StatusBar1.Height - 330 ProgressBar1.Left = 0.25 * StatusBar1.Width ProgressBar1.Width = 0.75 * Me.Width - 250 a: End Sub |
Private Sub Combo1_Click() `轉到指定網址 WebBrowser1.Navigate Combo1.Text End Sub Private Sub Combo1_KeyDown(KeyCode As Integer, Shift As Integer) Dim I As Long Dim existed As Boolean If KeyCode = 13 Then If Left(Combo1.Text, 7) <> "http://"Then Combo1.Text = "http://"+ Combo1.Text End If WebBrowser1.Navigate Combo1.Text For I = 0 To Combo1.ListCount - 1 If Combo1.List(I) = Combo1.Text Then existed = True Exit For Else existed = False End If Next If Not existed Then Combo1.AddItem (Combo1.Text) End If End If End Sub |
Private Sub WebBrowser1_DownloadBegin() `下載開始時狀態列顯示"Now Linking..." StatusBar1.SimpleText = "Now Linking..." End Sub |
Private Sub WebBrowser1_DownloadComplete() `下載完成時狀態列顯示"Link Finished" StatusBar1.SimpleText = "Link Finished" ProgressBar1.Value = 0 End Sub |
Private Sub WebBrowser1_ProgressChange(ByVal Progress As Long, ByVal ProgressMax As Long) `下載進行時進度條變化 If ProgressMax = 0 Then Exit Sub ProgressBar1.Max = ProgressMax If Progress <> -1 And Progress <= ProgressMax Then ProgressBar1.Value = Progress End If End Sub |
Private Sub WebBrowser1_TitleChange(ByVal Text As String) Combo1.Text = WebBrowser1.LocationURL End Sub |