winform 子线程进行弹窗提示

项目中有个动作:打开一个窗体展示

FormToast toast = new FormToast();
toast.lblMsg.Text = str;
toast.Show();

 


大多数情况,直接在界面上(主线程)点击按钮的时候展示,没问题。

有些特殊情况,是在新开的子线程中要展示窗体,用上面的办法就不行了,窗体展示不全,像被挡住或卡住。

网上找到了解决的办法:https://stackoverflow.com/questions/11995466/c-sharp-calling-form-show-from-another-thread

本例的写法如下:

复制代码
public static void hint(Form parent, string str)
{
FormToast toast = new FormToast();
//父窗体主线程中执行子窗体的属性操作 parent.Invoke((MethodInvoker)
delegate () { toast.lblMsg.Text = str; toast.Show(); });
}

public static void close(Form parent, string str)
{
FormToast toast = new FormToast();
//父窗体主线程中执行子窗体的属性操作 parent.Invoke(new Action<string>(

(str) =>{
  
this.close(); });

)
}
 
复制代码

 


把当时的窗体(姑且称为“父窗体”)拿过来,使用invoke方法。

 

问题解决。
窗口显示的时候使用主窗体的BeginInvoke方法用主线程执行弹出, 

 

posted @   JohnnyLei  阅读(644)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示