[英]Access parent windows form in backgroundworker
I have an extended method for messagebox.Show()
, which uses IWin32Window
of the parent winform to center the MessageBox
on it. 我有一个
messagebox.Show()
的扩展方法,该方法使用父Winform的IWin32Window
将MessageBox
置于其中心。
However, I can't seem to understand how can we possibly use this same extension method to pop-up MessageBox
on the main/parent winform from within BackgroundWorker
. 但是,我似乎无法理解我们如何才能使用相同的扩展方法从
BackgroundWorker
内部的主/父winform上弹出MessageBox
。
The extension method is something like this: 扩展方法是这样的:
MessageBoxExTn.Show(IWin32Window parentForm, string MsgText, string Caption, MessageBoxButtons);
I mean, I want to call this method from BackgroundWorker's
DoWork
event with threadsafe access to the parent/main winform. 我的意思是,我想从
BackgroundWorker's
DoWork
事件中调用此方法,并通过线程安全访问父/主Winform。
You can add another method on your Main Form and do something like this 您可以在主窗体上添加其他方法,然后执行以下操作
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);
}
please take a look at Control.InvokeRequired to understand more thread-safe in windows form 请查看Control.InvokeRequired以了解Windows窗体中的更多线程安全
call your code 调用您的代码
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ShowMessage();
}
You could use event in this case and fire event when you want to show the message box. 您可以在这种情况下使用事件,并在想要显示消息框时触发事件。 Now in your parent/main form handle this event and show the message box.
现在,在您的父/主窗体中处理此事件并显示消息框。 This way you can achieve this.
这样您就可以实现这一目标。
You need to leverage the BackgroundWorker
event ProgressChanged
. 您需要利用
BackgroundWorker
事件ProgressChanged
。 This will do the thread switching for you. 这将为您执行线程切换。 So imagine something like this:
因此,想象一下这样的事情:
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
MessageBoxExTn.Show(parentForm,
e.UserState as string,
someCaption,
MessageBoxButtons.OK);
}
and that's called like this: 就像这样:
backgroundWorker1.ReportProgress(1, "The message you want displayed.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.