2014-01-14 13 views
1

我有一個擴展方法messagebox.Show(),它使用父winform的IWin32Window來集中MessageBox在後臺工作中訪問父窗口

但是,我似乎無法理解我們怎麼可能使用這種相同的擴展方法從BackgroundWorker內彈出主/從winform上的MessageBox

擴展方法是這樣的:

MessageBoxExTn.Show(IWin32Window parentForm, string MsgText, string Caption, MessageBoxButtons); 

我的意思是,我想打電話從BackgroundWorker'sDoWork情況下,本方法與線程訪問父/主WinForm的。

回答

0

您可以在主窗體上添加一個方法,做這樣的事情

public void ShowMessage(string cap,string message) 
    { 
     if (this.InvokeRequired) 
     { 
      Action<string, string> action = ShowMessage; 
      this.Invoke(action, new object[] {cap, message}); 
      return; 
     } 

     MessageBoxExTn.Show(IWin32Window parentForm, string MsgText, string Caption, MessageBoxButtons); 
    } 

請看看Control.InvokeRequired瞭解更多的線程安全的Windows窗體

調用代碼

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
     { 
      ShowMessage(); 
     } 
0

您可以在這種情況下使用事件並在想要顯示消息框時觸發事件。現在在您的父/主窗體中處理此事件並顯示消息框。這樣你就可以做到這一點。

0

您需要利用BackgroundWorker事件ProgressChanged。這將爲你做線程切換。所以,想象這樣的事情:

private void backgroundWorker1_ProgressChanged(object sender, 
    ProgressChangedEventArgs e) 
{ 
    MessageBoxExTn.Show(parentForm, 
     e.UserState as string, 
     someCaption, 
     MessageBoxButtons.OK); 
} 

,並且被稱爲是這樣的:

backgroundWorker1.ReportProgress(1, "The message you want displayed.");