当前位置:编程学习 > C#/ASP.NET >>

C#接收,跪求各位大哥大姐帮忙啊!!

VS2008,C#界面就一个TextBox,要求用serial类事件和委托发送和接收,接收串口数据存入一字符数组并转换成字符串TextBox显示,项目中急要。自己看了一天C#事件和委托都没看懂,!!!!!!哪位好心人帮我写下,合适晚上就给分!!谢谢 --------------------编程问答--------------------
接分 --------------------编程问答--------------------

using System;
using System.IO.Ports;
using System.Threading;

public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;

    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message) );
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {
            try
            {
                string message = _serialPort.ReadLine();
                Console.WriteLine(message);
            }
            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

        Console.WriteLine("Available Ports:");
        foreach (string s in SerialPort.GetPortNames())
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("COM port({0}): ", defaultPortName);
        portName = Console.ReadLine();

        if (portName == "")
        {
            portName = defaultPortName;
        }
        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
        baudRate = Console.ReadLine();

        if (baudRate == "")
        {
            baudRate = defaultPortBaudRate.ToString();
        }

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        Console.WriteLine("Available Parity options:");
        foreach (string s in Enum.GetNames(typeof(Parity)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Parity({0}):", defaultPortParity.ToString());
        parity = Console.ReadLine();

        if (parity == "")
        {
            parity = defaultPortParity.ToString();
        }

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        Console.Write("Data Bits({0}): ", defaultPortDataBits);
        dataBits = Console.ReadLine();

        if (dataBits == "")
        {
            dataBits = defaultPortDataBits.ToString();
        }

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        Console.WriteLine("Available Stop Bits options:");
        foreach (string s in Enum.GetNames(typeof(StopBits)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
        stopBits = Console.ReadLine();

        if (stopBits == "")
        {
            stopBits = defaultPortStopBits.ToString();
        }

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        Console.WriteLine("Available Handshake options:");
        foreach (string s in Enum.GetNames(typeof(Handshake)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Handshake({0}):", defaultPortHandshake.ToString());
        handshake = Console.ReadLine();

        if (handshake == "")
        {
            handshake = defaultPortHandshake.ToString();
        }

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}

--------------------编程问答-------------------- 硬是没懂你要写啥?? --------------------编程问答-------------------- 接 分 --------------------编程问答-------------------- C#串口编程 --------------------编程问答-------------------- 2楼代码挺长,好晕。。。 --------------------编程问答-------------------- 这是一个委托 通用类

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace test
{
    public class FormControl
    {
        delegate void UpdateTextSafe(Control c,string text);
        delegate void UpdateEnableSafe(Control c, bool bEnable);
        delegate string GetTextSafe(Control c);
        delegate void ChageTextColorSafe(Control c, System.Drawing.Color str); //改变颜色
        delegate void ChageImageSafe(Control c, System.Drawing.Image str);  //改变图片
        delegate void UpdateDataSafe(Control c, string str1, string str2, string str3, string str4, string str5, string str6);//列表显示

        public FormControl()
        {
        }

      
        public void SetPicture(Control obj, System.Drawing.Image str)
        {
            ChageImageSafe slt = new ChageImageSafe(SetPicture);

            Control c = obj;
            if (c.InvokeRequired)
            {
                c.BeginInvoke(slt, new object[] { c, str });
            }
            else
            {
                c.BackgroundImage = str;
            }
        }

        public void SetColor(Control obj, System.Drawing.Color str)
        {
            ChageTextColorSafe slt = new ChageTextColorSafe(SetColor);

            Control c = obj;
            if (c.InvokeRequired)
            {
                c.BeginInvoke(slt, new object[] { c, str });
            }
            else
            {
                c.ForeColor = str;
            }
        }

      

        public void SetText(Control obj, string str)
        {
            UpdateTextSafe slt = new UpdateTextSafe(SetText);

            Control c = obj;
            if (c.InvokeRequired)
            {
                c.BeginInvoke(slt, new object[] {c, str });
            }
            else
            {
                c.Text = str;
            }
        }
       

        public void SetButton(Control obj, bool bEnable)
        {
            UpdateEnableSafe slt = new UpdateEnableSafe(SetButton);

            Control c = obj;
            if (c.InvokeRequired)
            {
                c.BeginInvoke(slt, new object[] {c, bEnable });
            }
            else
            {
                c.Enabled = bEnable;
            }
        }

        public string GetText(Control obj)
        {
            GetTextSafe slt = new GetTextSafe(GetText);

            Control c = obj;
            if (c.InvokeRequired)
            {
                c.BeginInvoke(slt, new object[] { c });
            }
            else
            {
                return c.Text;
            }
            return c.Text;
        }

    }
}


调用的时候可以这样
FormControl fc=new FormControl();
fc.SetText(label1,"测试");


串口通信

      
            sp.PortName = DutouCom;
            sp.BaudRate = Convert.ToInt32(DutouBaudRate);
            sp.ReadTimeout = 5000;//5秒后时间过期  
            sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);

            try
            {
                sp.Open();
             }
catch()
{

} --------------------编程问答-------------------- 帮你顶!加油帮你顶!加油 --------------------编程问答-------------------- 牛人真不少,看见这么多代码头都晕。
帮你顶起! --------------------编程问答-------------------- 关注中 --------------------编程问答-------------------- 关注中。 --------------------编程问答-------------------- 我有这儿有vb.net写的 demo
给我你的Email 我发给你。 --------------------编程问答-------------------- 关注中。。 --------------------编程问答-------------------- 楼主大意应该是这样的:
  1、用 System.IO.Ports.SerialPort  接收数据,并显示在TextBox中
  2、必须用事件接收,在事件中更新TextBox的内容
而 System.IO.Ports.SerialPort  的事件是异步的,不能直接在事件中对TextBox进行赋值,所以用到委托。

理解没有错的话,那么问题就简单了,楼主你先别管什么委托,程序该怎么写就怎么写,最后把对TextBox赋值的那句话改一下即可。
只要写一个更新TextBox的委托:

        //用于显示文本的委托类型
        private delegate void SetTextBoxtxt(TextBox tb,String txt);

        //委托的函数用于更新文本框内容
        private void settextboxtxt(TextBox tb,String txt)
        {
            tb.Text=txt;
        }

然后在你的函数中更新TextBox内容部分,把"textBox1.Text=XXX;"改成下面几句(假定XXX是你收到的字符串):

        SetTextBoxtxt stxt = new SetTextBoxtxt(settextboxtxt);
        Invoke(stxt, new object[] { TextBox1, XXXX });


--------------------编程问答-------------------- 帮顶,学习中,委托这东西,看了我好长时间,还是不太明白,呵呵 --------------------编程问答--------------------
引用 15 楼 xingjibing 的回复:
帮顶,学习中,委托这东西,看了我好长时间,还是不太明白,呵呵


委托这东西,就是指向函数的指针。 --------------------编程问答-------------------- 串口调试工具,发送字符串,程序中接受啊 --------------------编程问答-------------------- 占座学习 --------------------编程问答-------------------- 友情接分! --------------------编程问答-------------------- 你没在服务端挂起listen吧。。。

我记得是不是和你说过了?

你没挂listent  

send的时候,肯定接受不了。
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,