2010-04-07 72 views

回答

9

只需使用GET或類似的方式下載/favicon.ico文件(就像您對任何其他文件一樣)。
您也可以解析頁面,找到可能也是一個PNG的圖標。默認情況下它是一個ICO文件。

favicon文件的位置通常位於頁面的<head>節點中的<link rel="shortcut icon" href="/favicon.ico" />

此外,一些瀏覽器默認情況下嘗試下載/favicon.ico(即,在網站的根文件夾中的favicon.ico文件)沒有檢查該元素的網頁。

其他的想法是使用谷歌的S2:

http://www.google.com/s2/favicons?domain=youtube.com(Try it)
這將讓你YouTube的ICO圖標的16x16的PNG圖像

http://www.google.com/s2/favicons?domain=stackoverflow.com(Try it)
這將使您獲得相同格式的stackoverflow圖標。

它看起來很棒,但別忘了,此Google服務尚未官方支持,他們可能隨時將其刪除。

1

favicon單獨的文件。它不是頁面HTML的一部分。

您需要在單獨的調用中獲取它。

2

而webbrowser控件沒有地址欄,所以它沒有像favicon這樣的地址欄功能的應用程序編程接口。

+0

+1對於沒有實現此功能的控件 – 2010-04-14 13:11:17

0

我也需要這樣做,所以我寫了這個。請注意,我使用的是原生WebBrowser COM控件而不是.Net包裝器,因此如果您使用.Net包裝器,則需要進行一些小調整。

private void axWebBrowser1_DocumentComplete(object sender, AxSHDocVw.DWebBrowserEvents2_DocumentCompleteEvent e) 
{ 
    try 
    { 
     Uri url = new Uri((string)e.uRL); 
     string favicon = null; 
     mshtml.HTMLDocument document = axWebBrowser1.Document as mshtml.HTMLDocument; 
     if(document != null) 
     { 
      mshtml.IHTMLElementCollection linkTags = document.getElementsByTagName("link"); 
      foreach(object obj in linkTags) 
      { 
       mshtml.HTMLLinkElement link = obj as mshtml.HTMLLinkElement; 
       if(link != null) 
       { 
        if(!String.IsNullOrEmpty(link.rel) && !String.IsNullOrEmpty(link.href) && 
         link.rel.Equals("shortcut icon",StringComparison.CurrentCultureIgnoreCase)) 
        { 
         //TODO: Bug - Can't handle relative favicon URL's 
         favicon = link.href; 
        } 
       } 
      } 
     } 
     if(String.IsNullOrEmpty(favicon) && !String.IsNullOrEmpty(url.Host)) 
     { 
      if(url.IsDefaultPort) 
       favicon = String.Format("{0}://{1}/favicon.ico",url.Scheme,url.Host); 
      else 
       favicon = String.Format("{0}://{1}:{2}/favicon.ico",url.Scheme,url.Host,url.Port); 
     } 
     if(!String.IsNullOrEmpty(favicon)) 
     { 
      WebRequest request = WebRequest.Create(favicon); 
      request.BeginGetRequestStream(new AsyncCallback(SetFavicon), request); 
     } 
    } 
    catch 
    { 
     this.Icon = null; 
    } 
} 

private void SetFavicon(IAsyncResult result) 
{ 
    WebRequest request = (WebRequest)result.AsyncState; 
    WebResponse response = request.GetResponse(); 
    Bitmap bitmap = new Bitmap(Image.FromStream(response.GetResponseStream())); 
    this.Icon = Icon.FromHandle(bitmap.GetHicon()); 
} 
相關問題