public partial class UCInfo : UserControl { public UCInfo() { InitializeComponent(); } ManualResetEvent neverSetEvt = new ManualResetEvent(false); delegate void InvokeDelegate(); public void SetInfo(string info) { lblInfo.Invoke(new InvokeDelegate(() => { lblInfo.ForeColor = Color.Green; }), null); lblInfo.Invoke(new InvokeDelegate(() => { lblInfo.Text = info; }), null); ThreadPool.RegisterWaitForSingleObject(neverSetEvt, (obj, bol) => { if (lblInfo.IsHandleCreated) { lblInfo.Invoke(new InvokeDelegate(() => { lblInfo.Text = ""; }), null); } }, null, 600000, true); } public void SetInfo(string info, Color color) { lblInfo.Invoke(new InvokeDelegate(() => { lblInfo.ForeColor = color; }), null); lblInfo.Invoke(new InvokeDelegate(() => { lblInfo.Text = info; }), null); ThreadPool.RegisterWaitForSingleObject(neverSetEvt, (obj, bol) => { if (lblInfo.IsHandleCreated) { lblInfo.Invoke(new InvokeDelegate(() => { lblInfo.Text = ""; }), null); } }, null, 600000, true); } }
当调试运行中突然关闭软件时,
lblInfo.Invoke(labchange);语句就出先了“在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke。”错误。
解决办法是在lblInfo.Invoke(labchange);前加一个if(lblInfo.IsHandleCreated)判断就可以了