| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 565 人关注过本帖
标题:请教一个关于委托与事件的问题
只看楼主 加入收藏
rookie108
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2013-2-8
收藏
 问题点数:0 回复次数:3 
请教一个关于委托与事件的问题
我在一个关于串口操作的项目里,利用一个窗体来对串口进行读写操作。
config.cs窗体用来设置参数及收发指令。
Comm.cs类用来执行收发工作。
我的想法是当串口接收到数据后,config.cs窗体上自动弹出一个MessageBox。我采用了委托与事件方式。
代码如下,现在的问题是:在config.cs中设置串口参数及发送指令都正常,但是接收就不行了,用断点监控Comm.cs文件,可以确定串口是有接收有内容,但就是无法反馈到config.cs窗体上并自动弹出MessageBox.

不好意思,初学c#,对事件和委托感到很糊涂。总找不出问题出在哪里。还望高手们指点下迷津啊。


config.cs窗体代码:
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SerialPort_WR
{
    public partial class Config : Form
    {
        private Comm comm;
        public string spName;//serialPort.PortName
        public int spBaudRate;//serialPort.BaudRate
        public spStopBits;//serialPort.StopBits;
        public int spDataBits;//serialPort.DataBits
        public spHandShake;//serialPort.HandShake
        public spParity;//serialPort.Parity;

        public Config()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            PortSetupInit();
        }

        public void PortSetupInit()
        {   
            //扫描所有串口
            foreach (string P in ())
            {
                cB_PortName.Items.Add(P);
            }
            cB_PortName.SelectedIndex = 1;
            cB_BaudRate.SelectedIndex = 9;//波特率
            cB_DataBits.SelectedIndex = 3;//数据位
            cB_Handshake.SelectedIndex = 2;//流控制
            cB_Parity.SelectedIndex = 0;//校验位
            cB_StopBits.SelectedIndex = 0;//停止位
            cB_SchTak.SelectedIndex = 0;//查询时间
            //serialPort1.RtsEnable = true;
            //serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");//指定字符集,使之能发送中文
        }

        void comm_HaveDataReady(string RevCmd, String RevData)//这里设置了断点,总是无法执行这一行。问题可能出在这里。
        {
            this.BeginInvoke(new Comm.DataEventHandler(DataReady), new object[]{RevCmd,RevData});
        }

        void DataReady(string RevCmd, String RevData)
        {
            MessageBox.Show(RevCmd, RevData);
        }

        private void ConfigSave_Click(object sender, EventArgs e)
        {
            if (comm != null)
            {
                if (comm.IsOpen())
                {
                    comm.Close();
                }
                else
                {
                    comm.Open();
                }
            }
            else
            {
                SPSetup();
                comm = new Comm(spName, spBaudRate, spParity, spDataBits, spStopBits, spHandShake);
                comm.HaveDataReady += new Comm.DataEventHandler(comm_HaveDataReady);
                comm.Open();
                ConfigSave.Text = "关闭串口";
            }

        }



        public void SPSetup()
        {
            spName = cB_PortName.Text;
            spBaudRate = Convert.ToInt32(cB_BaudRate.Text);
            spDataBits = Convert.ToInt16(cB_DataBits.Text);
            switch (cB_StopBits.SelectedItem.ToString())//设置停止位
            {
                case "1":
                    spStopBits =
                    break;
                case "1.5":
                    spStopBits =
                    break;
                case "2":
                    spStopBits =
                    break;
            }
            switch (cB_Handshake.SelectedItem.ToString())//设置流控制
            {
                case "HARDWARE":
                    spHandShake =
                    break;
                case "SOFTWARE":
                    spHandShake =
                    break;
                case "NONE":
                    spHandShake =
                    break;
                case "Custom":
                    spHandShake =
                    break;
            }
            switch (cB_Parity.SelectedItem.ToString())//设置校验位
            {
                case "None":
                    spParity =
                    break;
                case "Odd":
                    spParity =
                    break;
                case "Even":
                    spParity =
                    break;
                case "Mark":
                    spParity =
                    break;
                case "Space":
                    spParity =
                    break;
            }
        }

        private void bT_Clear_Click(object sender, EventArgs e)
        {
            //tB_Receive.Clear();
            //Comm com = new Comm(spName, spBaudRate, spParity, spDataBits, spStopBits, spHandShake);

            tB_Receive.Text += comm.s2;
        }

        private void tB_Receive_TextChanged(object sender, System.EventArgs e)
        {
            if (tB_Receive.Text.Length > 0)
            {
                tB_Receive.Select(tB_Receive.Text.Length - 1, 0);   // 如果有換行的数据时,会在最后一行产生空行。
                tB_Receive.ScrollToCaret();
            }
        }

        public void bT_SendMsg_Click(object sender, EventArgs e)
        {
            comm.SendMsg(tB_PhoneNo.Text, tB_Msg.Text);
        }


        private void Delay(int mm)
        {
            DateTime current = DateTime.Now;

            while (current.AddMilliseconds(mm) > DateTime.Now)
            {
                Application.DoEvents();
            }
            return;
        }

        private void Config_Resize(object sender, EventArgs e)
        {
           this.FormBorderStyle =System.Windows.Forms.FormBorderStyle.None;
        }
    }

Comm.cs文件代码:

using System.Text;
using System;
using System.Threading;
using
using
using System.Windows.Forms;

public class Comm
{
    private SerialPort port;
    private byte[] readcache;
    private int idx;
    public string SendOK;
    public string s2;
    public string s3;

    public delegate void DataEventHandler(string RevCmd, string RevData);
    public event DataEventHandler HaveDataReady;

    public Comm(string spName, int spBaudRate, Parity spParity, int spDataBits, StopBits spStopBits, Handshake spHandShake)
    {
        port = new SerialPort(spName, spBaudRate, spParity, spDataBits, spStopBits);
        port.Handshake = spHandShake;
        port.ReadTimeout = 500;
        port.WriteTimeout = 500;
        port.ReadBufferSize = 1024;
        port.ReceivedBytesThreshold = 1;

        port.DataReceived += new SerialDataReceivedEventHandler(portDataReceived);
        readcache = new byte[256];
        idx = 0;
    }

    public bool IsOpen()
    {
        return port.IsOpen;
    }
    public void Open()
    {
        port.Open();
    }
    public void Close()
    {
        port.Close();
    }

    public void portDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            byte inputData = 0;
            while ((port.BytesToRead > 0))
            {
                inputData = (byte)port.ReadByte();
               
                if (inputData.Equals(0xa))
                {
                    idx = 0;
                }
                else if (inputData.Equals(0xd))
                {
                    byte[] b = new byte[idx];
                    Array.Copy(readcache, b, idx);
                    s2 = Encoding.ASCII.GetString(b);
                    st(s2);
                    idx = 0;

                }
                else
                {
                    readcache[idx] = inputData;
                    idx++;
                    idx %= 1024;
                }
            }
        }
        catch
        {
        }

        
    }
    public void st(string s2)
    {
        s3 = s2;
    }

    public void SendMsg(string phone, string msg)
    {
       port.WriteLine(phone);
       port.WriteLine(msg);

    }

    private void Delay(int mm)
    {
        DateTime current = DateTime.Now;

        while (current.AddMilliseconds(mm) > DateTime.Now)
        {
            Application.DoEvents();
        }
        return;
    }

}
搜索更多相关主题的帖子: 断点 
2013-02-08 11:53
rookie108
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2013-2-8
收藏
得分:0 
问题解决了。所以终止该贴。原来是要在Comm类里接收信息代码处加上抛起事件
2013-02-08 12:16
不玩虚的
Rank: 9Rank: 9Rank: 9
来 自:四川
等 级:贵宾
威 望:10
帖 子:331
专家分:1301
注 册:2012-12-9
收藏
得分:0 
同学习 共进步

同学习......同进步....你帮我......我帮你.....上善若水.....
2013-02-12 00:08
baikil
Rank: 10Rank: 10Rank: 10
来 自:X星球
等 级:青峰侠
威 望:4
帖 子:282
专家分:1580
注 册:2009-7-20
收藏
得分:0 
public class Comm 中声明了  public event DataEventHandler HaveDataReady; 未使用过

在 public void portDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            byte inputData = 0;
            while ((port.BytesToRead > 0))
            {
                inputData = (byte)port.ReadByte();
               
                if (inputData.Equals(0xa))
                {
                    idx = 0;
                }
                else if (inputData.Equals(0xd))
                {
                    byte[] b = new byte[idx];
                    Array.Copy(readcache, b, idx);
                    s2 = Encoding.ASCII.GetString(b);
                    st(s2);
                    idx = 0;

                }
                else
                {
                    readcache[idx] = inputData;
                    idx++;
                    idx %= 1024;
                }
            }
         //加个
           if(HaveDataReady!=null)
            {
                 HaveDataReady("","");//写入你要传出的参数
            }
        }
        catch
        {
        }

        
    }

自创QQ群64885635,方便C#学习交流.希望各项工作路好学都好入!
2013-02-16 09:10
快速回复:请教一个关于委托与事件的问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019735 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved