2008-10-27 33 views
1

我目前正試圖建立一個簡單的組件,它應該監視,如果用戶打開一個具有特定URL(僅限IE)的窗口。 所以我寫了這個組件,一切正常,所以我將它與應用程序集成在一起,它需要它。 問題是,在這個應用程序中使用了PerformanceCounters,並且這些似乎干擾了InternetExplorer自動化對象的行爲。InternetExplorer自動化對象+ PerformanceCounter =不工作?

所以我寫了這個小樣本來演示該問題:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Threading; 
using System.Diagnostics; 
using SHDocVw; 

namespace IEHookTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Thread t = new Thread(PerfCounter); 
      t.Start(); 

      URLInterceptor.Instance.StartListening(); 
      Console.ReadLine(); 
     } 

     private static void PerfCounter() 
     { 
      PerformanceCounter cpuPc = 
       new PerformanceCounter("Processor", "% Processor Time", "_Total", true); 
      do 
      { 
       float x = cpuPc.NextValue(); 
       System.Diagnostics.Debug.WriteLine(x); 
       Thread.Sleep(50); 
      } while (true); 
     } 
    } 

    class URLInterceptor 
    { 
     private const string DEMANDED_URL = "test"; 
     private ShellWindows _shellWindows = new ShellWindows(); 

     public static readonly URLInterceptor Instance = new URLInterceptor(); 
     private static int _count = 0; 
     private URLInterceptor() 
     { 
     } 

     public void StartListening() 
     { 
      _count++; 
      _shellWindows.WindowRegistered -= ShellWindows_WindowRegistered; 
      _shellWindows.WindowRegistered += new DShellWindowsEvents_WindowRegisteredEventHandler(ShellWindows_WindowRegistered); 
      FindIEs(); 
     } 

     private void FindIEs() 
     { 
      int count = 0; 
      foreach (InternetExplorer browser in _shellWindows) 
      { 
       browser.NewWindow3 -= browser_NewWindow3; 
       browser.NewWindow3 += new DWebBrowserEvents2_NewWindow3EventHandler(browser_NewWindow3); 
       count++; 
      } 
     } 

     private void ShellWindows_WindowRegistered(int lCookie) 
     { 
      FindIEs(); 
     } 

     private void browser_NewWindow3(ref object ppDisp, 
             ref bool Cancel, 
             uint dwFlags, 
             string bstrUrlContext, 
             string bstrUrl) 
     { 
      if (!string.IsNullOrEmpty(bstrUrl) && bstrUrl.ToLower().Contains(DEMANDED_URL)) 
      { 
       Cancel = true; 
       Console.WriteLine("catched URL: " + bstrUrl); 
      } 
     } 
    } 
} 

此示例需要在「Microsoft Internet控制」(SHDOCVW)的參考。 要測試樣本,只需打開谷歌搜索「測試」。採取第一個鏈接,並在一個新的選項卡或窗口中打開它。 你會看到,有時會引發「NewWindow3」事件,有時不會。 但是,如果您註釋掉第15行(線程啓動),則這些對象按預期工作,併爲每個新窗口引發該事件。

所以我的問題是,爲什麼性能計數器會打擾InternetExplorer對象,我該如何使用它們。我試圖在一個新的AppDomain中運行監視器組件,但這並沒有解決問題。只有創建一個新流程纔是解決方案,但這是我不想做的,原因有幾個。

我測試WIN2K3服務器上用IE 7

回答

0

爲了保持引用在一個ArrayList解決了這個問題。似乎ShellWindows集合不包含引用。