2008-10-28 98 views
2

我正在爲IE(6+)編寫一個工具欄。我用可能的線程/ COM/UI問題

codeproject.com(http://www.codeproject.com/KB/dotnet/IE_toolbar.aspx),並有一個工作的工具欄,註冊取消註冊等。我想要的工具欄要做的是突出顯示html頁面內的div作爲用戶的鼠標移動該div。到目前爲止,突出顯示的代碼工作,但我想顯示在工具欄上的標籤(如果它存在)的名稱(隨着鼠標移動等改變)。

我不能爲了我的生活得到這種事情發生並嘗試調試它是一場噩夢。由於程序集是在IE中進行託管的,我懷疑我是通過嘗試從沒有創建該控件的線程更新標籤上的文本而導致發生異常(在IE中),但是由於該例外發生在IE中,因此我看不到它。

是否嘗試使用Invoke以線程安全的方式更新控件的解決方案?如果是這樣如何?

這裏是事件代碼:

private void Explorer_MouseOverEvent(mshtml.IHTMLEventObj e) 
{ 
     mshtml.IHTMLDocument2 doc = this.Explorer.Document as IHTMLDocument2; 
     element = doc.elementFromPoint(e.clientX, e.clientY); 
     if (element.tagName.Equals("DIV", StringComparison.InvariantCultureIgnoreCase)) 
     { 
      element.style.border = "thin solid blue;"; 
      if (element.className != null) 
      { 
       UpdateToolstrip(element.className); 
      } 
     } 
     e.returnValue = false; 
} 

,這裏是在工具欄的線程安全更新的嘗試:

delegate void UpdateToolstripDelegate(string text); 

public void UpdateToolstrip(string text) 
{ 
    if (this.toolStripLabel1.InvokeRequired == false) 
    { 
     this.toolStripLabel1.Text = text; 
    } 
    else 
    { 
     this.Invoke(new UpdateToolstripDelegate(UpdateToolstrip), new object[] { text }); 
    } 
} 

任何建議非常讚賞。

回答

1

我真的不能重現問題(對於IE工具欄創建一個測試項目是一點點太多的工作),但你可以試試這個:

添加下列程序到公共靜態(擴展方法)類:

public static void Invoke(this Control control, MethodInvoker methodInvoker) 
{ 
    if (control.InvokeRequired) 
     control.Invoke(methodInvoker); 
    else 
     methodInvoker(); 
} 

然後用這個替代的類似的代碼段中的第一個塊:

if (element.className != null) 
{ 
    this.Invoke(() => toolStripLabel1.Text = element.className); 
} 

這是避免線程安全ISSU的最好方法在UI應用程序中。