private void OnMessage(string msg) { if (this.listBox1.InvokeRequired == false) { listBox1.Items.Add(msg); } else { DispMSGDelegate DMSGD = new DispMSGDelegate(OnMessage); this.listBox1.BeginInvoke(DMSGD, msg); } }
/// <summary> /// 定义一个函数,用于向窗体上的ListView控件添加内容 /// </summary> /// <param name="strMsg"></param> private void DispMsg(string strMsg) { if (this.lvDataList.InvokeRequired == false) { //直接将内容添加到窗体的控件上 ListViewItem lvi = new ListViewItem(); lvi.SubItems[0].Text = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); lvi.SubItems.Add(strMsg); this.lvDataList.Items.Insert(0, lvi); } else { DispMSGDelegate DMSGD = new DispMSGDelegate(DispMsg); this.lvDataList.Invoke(DMSGD, strMsg); } }
private void DispMsg(string strMsg) { string sendMsg = strMsg + "\n"; if (this.rTxtbox_Send.InvokeRequired == false) //如果调用该函数的线程和控件lstMain位于同一个线程内 { rTxtbox_Send.AppendText(strMsg); rTxtbox_Send.AppendText("\n"); } else //如果调用该函数的线程和控件lstMain不在同一个线程 { //通过使用Invoke的方法,让子线程告诉窗体线程来完成相应的控件操作 DispMSGDelegate DMSGD = new DispMSGDelegate(DispMsg); //使用控件lstMain的Invoke方法执行DMSGD代理(其类型是DispMSGDelegate) this.rTxtbox_Send.Invoke(DMSGD, strMsg); } }