using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace ByteToString
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button5.Enabled = false;
        }        private void button1_Click(object sender, EventArgs e)
        {
            byte[] b = new byte[4];
            b[0] = 0xaf;
            b[1] = 0xae;
            b[2] = 0xad;
            b[3] = 0xac;
            string strtotal = "";
            //   string strinter = "";            for (int x = 0; x < 4; x++)
            {
                string sr = Convert.ToInt32(b[x]).ToString("X");
                strtotal += sr + " ";
                //  strinter
            }
            //  MessageBox.Show(strtotal);
            richTextBox.AppendText(strtotal);
            richTextBox.Focus();
        }        private void button2_Click(object sender, EventArgs e)
        {
            richTextBox.Clear();
        }        private void button3_Click(object sender, EventArgs e)
        {
         //   this.Close();
          //  Application.Exit();
            serialPort.PortName = "com8";
            if (!serialPort.IsOpen)
            {
                serialPort.Open();
                button3.Enabled = false;
                button5.Enabled = true;
            }
        }        private void button4_Click(object sender, EventArgs e)
        {
            byte[] buff=new byte[4];            buff[0]=0xaf;            buff[1]=0xc4;            buff[2]=0xed;            buff[3]=0xfa;
            string strtotal = "";            for (int x = 0; x < 4; x++)
            {
                string sr = Convert.ToInt32(buff[x]).ToString("X");
                strtotal += sr + " ";
                //  strinter
            }
       //     serialPort.WriteLine(strtotal);
            if (serialPort.IsOpen)
            serialPort.Write(buff, 0, 4);            
        }        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
          //  serialPort
            byte[] buffer = new byte[serialPort.ReadBufferSize];
          //  string str = "";
            serialPort.Read(buffer, 0, serialPort.ReadBufferSize);
            
            string strtotal = "";
            //   string strinter = "";            for (int x = 0; x < serialPort.ReadBufferSize; x++)
            {
                string sr = Convert.ToInt32(buffer[x]).ToString("X");
                strtotal += sr + " ";
                //  strinter
            }
            //  MessageBox.Show(strtotal);
            richTextBox.AppendText(strtotal);
            richTextBox.Focus();        }        private void button5_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
                button3.Enabled = true;
                button5.Enabled = false;
            }
        }
    }
}
为什么使用串口接收时 函数richTextBox.AppendText(strtotal);
报错,提示“线程间操作无效: 从不是创建控件“richTextBox”的线程访问它。”错误,是不是应该使用委托?请问如果使用委托怎么搞?我还不会使用委托,麻烦哪位大虾给写出来贴一下!

解决方案 »

  1.   

    (1)、最好的方法是使用委托,因为它是线程安全的。
    (2)、偷懒的方法是在你的Form_Load事件中增加:
    Control.CheckForIllegalCrossThreadCalls = false;
      

  2.   

    那位兄弟能把完整的委托代码部分贴出来么?这几天是在是看不明太委托部分的东西!最好能将接收的显示在box中。
      

  3.   

    outPutBox.Invoke(new EventHandler(delegate
                {
                    outPutBox.AppendText(msg);
                    outPutBox.ScrollToCaret();
                }));
      

  4.   

    下边使用了委托,但是在函数 private void  SomeFunction(string str) 
            {
                richTextBox.AppendText(str);
                richTextBox.Focus();
            }
    地方报错了,还是从不是创建控件“richTextBox”的线程访问它。”请哪位高手看看,从哪里给我修正一下,能够使得这个接收并显示顺利!using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;namespace ByteToString
    {
        public partial class Form1 : Form
        {
    /// <summary>
    /// ///////////////////////////////////////////////////////////////
            /// Delegate int SomeDelegate(string s, bool b);
    /// </summary>
            private delegate void   sss(string str);        private void  SomeFunction(string str) 
            {
                richTextBox.AppendText(str);
                richTextBox.Focus();
            }        public Form1()
            {
                InitializeComponent();
                button5.Enabled = false;
            }        private void button1_Click(object sender, EventArgs e)
            {
                byte[] b = new byte[4];
                b[0] = 0xaf;
                b[1] = 0xae;
                b[2] = 0xad;
                b[3] = 0xac;
                string strtotal = "";
                //   string strinter = "";            for (int x = 0; x < 4; x++)
                {
                    string sr = Convert.ToInt32(b[x]).ToString("X");
                    strtotal += sr + " ";
                    //  strinter
                }
                //  MessageBox.Show(strtotal);
                richTextBox.AppendText(strtotal);
                richTextBox.Focus();
            }        private void button2_Click(object sender, EventArgs e)
            {
                richTextBox.Clear();
            }        private void button3_Click(object sender, EventArgs e)
            {
             //   this.Close();
              //  Application.Exit();
                serialPort.PortName = "com8";
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                    button3.Enabled = false;
                    button5.Enabled = true;
                }
            }        private void button4_Click(object sender, EventArgs e)
            {
                byte[] buff=new byte[4];            buff[0]=0xaf;            buff[1]=0xc4;            buff[2]=0xed;            buff[3]=0xfa;
                string strtotal = "";            for (int x = 0; x < 4; x++)
                {
                    string sr = Convert.ToInt32(buff[x]).ToString("X");
                    strtotal += sr + " ";
                    //  strinter
                }
           //     serialPort.WriteLine(strtotal);
                if (serialPort.IsOpen)
                serialPort.Write(buff, 0, 4);            
            }        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {
              //  serialPort
                byte[] buffer = new byte[serialPort.ReadBufferSize];
              //  string str = "";
                serialPort.Read(buffer, 0, serialPort.ReadBufferSize);
                
                string strtotal = "";
                //   string strinter = "";            for (int x = 0; x < serialPort.ReadBufferSize; x++)
                {
                    string sr = Convert.ToInt32(buffer[x]).ToString("X");
                    strtotal += sr + " ";
                    //  strinter
                }
                //  MessageBox.Show(strtotal);
            //    richTextBox.AppendText(strtotal);
          //      richTextBox.Focus();
    //
    ///test            sss sd = new sss(SomeFunction);
                sd("somestring");
            }        private void button5_Click(object sender, EventArgs e)
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                    button3.Enabled = true;
                    button5.Enabled = false;
                }
            }
        }
    }
      

  5.   

    不是你定义了一个委托,你就算使用委托了,委托有自己的写法 
    你不是定义了一个
    private delegate void  sss(string str);         private void  SomeFunction(string str) 
            { 
                richTextBox.AppendText(str); 
                richTextBox.Focus(); 
            } 你不能直接调用sss   
    你应该这么写
    this.Invoke(new sss(somefunction),new object[]{"XXX"});
      

  6.   

    先定义委托,然后定义具有相同参数和返回值的函数,名字没有实际意义,最后使用Invoke方法调用委托方法,就这么三个步骤。
      

  7.   

    如果是VS2008的话,写委托还可以更简单哦,我举个例子给你看看:        private void Form1_Load(object sender, EventArgs e)
            {
                Thread t = new Thread(showmessage);
                t.Start();
            }        void showmessage()
            {
                this.Invoke(printExplicit, "测试");
            }        Action<string> printExplicit = (string s) => MessageBox.Show(s);
      

  8.   

    多谢各位,尤其谢谢ttianqq 大虾,已经可以显示了我将这个完整的贴出来以便于其他不明白的兄弟参考
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;namespace ByteToString
    {
        public partial class Form1 : Form
        {
    /// <summary>
    /// ///////////////////////////////////////////////////////////////
            /// Delegate int SomeDelegate(string s, bool b);
    /// </summary>
            private delegate void   sss(string str);        private void  SomeFunction(string str) 
            {
                richTextBox.AppendText(str);
                richTextBox.Focus();
            }        public Form1()
            {
                InitializeComponent();
                button5.Enabled = false;
            }        private void button1_Click(object sender, EventArgs e)
            {
                byte[] b = new byte[4];
                b[0] = 0xaf;
                b[1] = 0xae;
                b[2] = 0xad;
                b[3] = 0xac;
                string strtotal = "";
                //   string strinter = "";            for (int x = 0; x < 4; x++)
                {
                    string sr = Convert.ToInt32(b[x]).ToString("X");
                    strtotal += sr + " ";
                    //  strinter
                }
                //  MessageBox.Show(strtotal);
                richTextBox.AppendText(strtotal);
                richTextBox.Focus();
            }        private void button2_Click(object sender, EventArgs e)
            {
                richTextBox.Clear();
            }        private void button3_Click(object sender, EventArgs e)
            {
             //   this.Close();
              //  Application.Exit();
                serialPort.PortName = "com8";
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                    button3.Enabled = false;
                    button5.Enabled = true;
                }
            }        private void button4_Click(object sender, EventArgs e)
            {
                byte[] buff=new byte[4];            buff[0]=0xaf;            buff[1]=0xc4;            buff[2]=0xed;            buff[3]=0xfa;
                string strtotal = "";            for (int x = 0; x < 4; x++)
                {
                    string sr = Convert.ToInt32(buff[x]).ToString("X");
                    strtotal += sr + " ";
                    //  strinter
                }
           //     serialPort.WriteLine(strtotal);
                if (serialPort.IsOpen)
                serialPort.Write(buff, 0, 4);            
            }        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {
              //  serialPort
                byte[] buffer = new byte[serialPort.ReadBufferSize];
              //  string str = "";
                serialPort.Read(buffer, 0, serialPort.ReadBufferSize);
                
                string strtotal = "";
                //   string strinter = "";            for (int x = 0; x < serialPort.ReadBufferSize; x++)
                {
                    string sr = Convert.ToInt32(buffer[x]).ToString("X");
                    strtotal += sr + " ";
                    //  strinter
                }
                //  MessageBox.Show(strtotal);
            //    richTextBox.AppendText(strtotal);
          //      richTextBox.Focus();
    //
    ///test            sss sd = new sss(SomeFunction);
                this.Invoke(new sss(SomeFunction), new object[] { "asdf" });        //    sd("somestring");
            }        private void button5_Click(object sender, EventArgs e)
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                    button3.Enabled = true;
                    button5.Enabled = false;
                }
            }
        }
    }
    其中最关键的一句是调用委托
    this.Invoke(new sss(SomeFunction), new object[] { "asdf" });