| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2272 人关注过本帖
标题:我下就是这个代码:
只看楼主 加入收藏
caifurain
Rank: 1
等 级:新手上路
帖 子:9
专家分:0
注 册:2008-1-28
收藏
 问题点数:0 回复次数:13 
我下就是这个代码:
要怎么在VS  2005中调试才不会出错啊?怎么拆分成Form.cs   Form1.designer.cs 和progam.cs??我拆分后怎么会出现我上一贴的问题?谢谢啊!请高手发到我的邮箱:hongcaifudyx@

using System;
using System.Drawing;
using System.Collections;
using
using System.Windows.Forms;
using System.Data;
using System.Threading;
namespace BusApp
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.Label label1;
  private System.Windows.Forms.Label label2;
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.GroupBox groupBox1;
  private System.Windows.Forms.Label label3;
  private System.Windows.Forms.Label label4;
  private System.Windows.Forms.Label label5;
  private System.Windows.Forms.Label label6;
  private System.Windows.Forms.Button button2;
  private System.Windows.Forms.Button button3;
  private System.Windows.Forms.Button button4;
  private System.Windows.Forms.TextBox textBox8;
  private System.Windows.Forms.Label label7;

  public int iPort=1; //1,2,3,4
  public int iRate=9600; //1200,2400,4800,9600
  public byte bSize=8; //8 bits
  public byte bParity=0; // 0-4=no,odd,even,mark,space
  public byte bStopBits=1; // 0,1,2 = 1, 1.5, 2
  public int iTimeout=1000;
  public mycom mycom1=new mycom();
  public byte[] recb;

  private System.Windows.Forms.TextBox msg;
  private System.Windows.Forms.TextBox t_port;
  private System.Windows.Forms.TextBox t_rate;
  private System.Windows.Forms.TextBox t_bytesize;
  private System.Windows.Forms.TextBox t_stopbyte;
  private System.Windows.Forms.TextBox t_parity;
  private System.Windows.Forms.TextBox t_send;
  private System.Windows.Forms.Button button5; //readTimeOut
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private components = null;

  public Form1()
  {
   InitializeComponent();
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.msg = new System.Windows.Forms.TextBox();
   this.label1 = new System.Windows.Forms.Label();
   this.label2 = new System.Windows.Forms.Label();
   this.t_send = new System.Windows.Forms.TextBox();
   this.button1 = new System.Windows.Forms.Button();
   this.groupBox1 = new System.Windows.Forms.GroupBox();
   this.button2 = new System.Windows.Forms.Button();
   this.t_port = new System.Windows.Forms.TextBox();
   this.label3 = new System.Windows.Forms.Label();
   this.t_rate = new System.Windows.Forms.TextBox();
   this.label4 = new System.Windows.Forms.Label();
   this.t_bytesize = new System.Windows.Forms.TextBox();
   this.label5 = new System.Windows.Forms.Label();
   this.t_stopbyte = new System.Windows.Forms.TextBox();
   this.label6 = new System.Windows.Forms.Label();
   this.t_parity = new System.Windows.Forms.TextBox();
   this.button3 = new System.Windows.Forms.Button();
   this.button4 = new System.Windows.Forms.Button();
   this.textBox8 = new System.Windows.Forms.TextBox();
   this.label7 = new System.Windows.Forms.Label();
   this.button5 = new System.Windows.Forms.Button();
   this.groupBox1.SuspendLayout();
   this.SuspendLayout();
   //
   // msg
   //
   this.msg.ForeColor = System.Drawing.Color.Green;
   this.msg.Location = new System.Drawing.Point(0, 0);
   this.msg.Multiline = true;
   this.msg.Name = "msg";
   this.msg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
   this.msg.Size = new System.Drawing.Size(512, 264);
   this.msg.TabIndex = 0;
   this.msg.Text = "";
   //
   // label1
   //
   this.label1.Location = new System.Drawing.Point(16, 24);
   this.label1.Name = "label1";
   this.label1.Size = new System.Drawing.Size(56, 16);
   this.label1.TabIndex = 1;
   this.label1.Text = "串口号:";
   //
   // label2
   //
   this.label2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)),

((System.Byte)(64)), ((System.Byte)(0)));
   this.label2.Location = new System.Drawing.Point(8, 280);
   this.label2.Name = "label2";
   this.label2.Size = new System.Drawing.Size(80, 16);
   this.label2.TabIndex = 1;
   this.label2.Text = "设置数据包:";
   //
   // t_send
   //
   this.t_send.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_send.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)),

((System.Byte)(128)), ((System.Byte)(0)));
   this.t_send.Location = new System.Drawing.Point(80, 272);
   this.t_send.Name = "t_send";
   this.t_send.Size = new System.Drawing.Size(344, 21);
   this.t_send.TabIndex = 2;
   this.t_send.Text = "";
   //
   // button1
   //
   this.button1.Location = new System.Drawing.Point(432, 272);
   this.button1.Name = "button1";
   this.button1.Size = new System.Drawing.Size(40, 23);
   this.button1.TabIndex = 3;
   this.button1.Text = "发送";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // groupBox1
   //
   this.groupBox1.Controls.Add(this.button2);
   this.groupBox1.Controls.Add(this.t_port);
   this.groupBox1.Controls.Add(this.label1);
   this.groupBox1.Controls.Add(this.label3);
   this.groupBox1.Controls.Add(this.t_rate);
   this.groupBox1.Controls.Add(this.label4);
   this.groupBox1.Controls.Add(this.t_bytesize);
   this.groupBox1.Controls.Add(this.label5);
   this.groupBox1.Controls.Add(this.t_stopbyte);
   this.groupBox1.Controls.Add(this.label6);
   this.groupBox1.Controls.Add(this.t_parity);
   this.groupBox1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)),

((System.Byte)(64)), ((System.Byte)(0)));
   this.groupBox1.Location = new System.Drawing.Point(8, 304);
   this.groupBox1.Name = "groupBox1";
   this.groupBox1.Size = new System.Drawing.Size(176, 216);
   this.groupBox1.TabIndex = 4;
   this.groupBox1.TabStop = false;
   this.groupBox1.Text = "参数设置";
   //
   // button2
   //
   this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
   this.button2.Location = new System.Drawing.Point(80, 184);
   this.button2.Name = "button2";
   this.button2.TabIndex = 3;
   this.button2.Text = "应用设置";
   this.button2.Click += new System.EventHandler(this.button2_Click);
   //
   // t_port
   //
   this.t_port.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_port.Location = new System.Drawing.Point(80, 16);
   this.t_port.Name = "t_port";
   this.t_port.Size = new System.Drawing.Size(80, 21);
   this.t_port.TabIndex = 2;
   this.t_port.Text = "1";
   //
   // label3
   //
   this.label3.Location = new System.Drawing.Point(16, 58);
   this.label3.Name = "label3";
   this.label3.Size = new System.Drawing.Size(56, 16);
   this.label3.TabIndex = 1;
   this.label3.Text = "波特率:";
   //
   // t_rate
   //
   this.t_rate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_rate.Location = new System.Drawing.Point(80, 50);
   this.t_rate.Name = "t_rate";
   this.t_rate.Size = new System.Drawing.Size(80, 21);
   this.t_rate.TabIndex = 2;
   this.t_rate.Text = "9600";
   //
   // label4
   //
   this.label4.Location = new System.Drawing.Point(16, 92);
   this.label4.Name = "label4";
   this.label4.Size = new System.Drawing.Size(56, 16);
   this.label4.TabIndex = 1;
   this.label4.Text = "数据位:";
   //
   // t_bytesize
   //
   this.t_bytesize.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_bytesize.Location = new System.Drawing.Point(80, 84);
   this.t_bytesize.Name = "t_bytesize";
   this.t_bytesize.Size = new System.Drawing.Size(80, 21);
   this.t_bytesize.TabIndex = 2;
   this.t_bytesize.Text = "8";
   //
   // label5
   //
   this.label5.Location = new System.Drawing.Point(16, 126);
   this.label5.Name = "label5";
   this.label5.Size = new System.Drawing.Size(56, 16);
   this.label5.TabIndex = 1;
   this.label5.Text = "停止位:";
   //
   // t_stopbyte
   //
   this.t_stopbyte.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_stopbyte.Location = new System.Drawing.Point(80, 118);
   this.t_stopbyte.Name = "t_stopbyte";
   this.t_stopbyte.Size = new System.Drawing.Size(80, 21);
   this.t_stopbyte.TabIndex = 2;
   this.t_stopbyte.Text = "1";
   //
   // label6
   //
   this.label6.Location = new System.Drawing.Point(16, 160);
   this.label6.Name = "label6";
   this.label6.Size = new System.Drawing.Size(56, 16);
   this.label6.TabIndex = 1;
   this.label6.Text = "校验位:";
   //
   // t_parity
   //
   this.t_parity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.t_parity.Enabled = false;
   this.t_parity.Location = new System.Drawing.Point(80, 152);
   this.t_parity.Name = "t_parity";
   this.t_parity.Size = new System.Drawing.Size(80, 21);
   this.t_parity.TabIndex = 2;
   this.t_parity.Text = "0";
   //
   // button3
   //
   this.button3.Location = new System.Drawing.Point(472, 272);
   this.button3.Name = "button3";
   this.button3.Size = new System.Drawing.Size(40, 23);
   this.button3.TabIndex = 3;
   this.button3.Text = "清空";
   this.button3.Click += new System.EventHandler(this.button3_Click);
   //
   // button4
   //
   this.button4.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
   this.button4.Location = new System.Drawing.Point(432, 312);
   this.button4.Name = "button4";
   this.button4.Size = new System.Drawing.Size(72, 23);
   this.button4.TabIndex = 6;
   this.button4.Text = "初始化";
   //
   // textBox8
   //
   this.textBox8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
   this.textBox8.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)),

((System.Byte)(128)), ((System.Byte)(0)));
   this.textBox8.Location = new System.Drawing.Point(288, 312);
   this.textBox8.Name = "textBox8";
   this.textBox8.Size = new System.Drawing.Size(136, 21);
   this.textBox8.TabIndex = 7;
   this.textBox8.Text = "";
   //
   // label7
   //
   this.label7.Location = new System.Drawing.Point(200, 320);
   this.label7.Name = "label7";
   this.label7.Size = new System.Drawing.Size(100, 16);
   this.label7.TabIndex = 8;
   this.label7.Text = "设置本机地址:";
   //
   // button5
   //
   this.button5.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
   this.button5.Location = new System.Drawing.Point(440, 504);
   this.button5.Name = "button5";
   this.button5.Size = new System.Drawing.Size(64, 23);
   this.button5.TabIndex = 9;
   this.button5.Text = "关闭串口";
   this.button5.Click += new System.EventHandler(this.button5_Click);
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(512, 533);
   this.Controls.Add(this.button5);
   this.Controls.Add(this.textBox8);
   this.Controls.Add(this.label7);
   this.Controls.Add(this.button4);
   this.Controls.Add(this.groupBox1);
   this.Controls.Add(this.button1);
   this.Controls.Add(this.t_send);
   this.Controls.Add(this.msg);
   this.Controls.Add(this.label2);
   this.Controls.Add(this.button3);
   this.Name = "Form1";
   this.Text = "串口通讯(小y设计)";
   this.Closing += new (this.Form1_Closing);
   this.Load += new System.EventHandler(this.Form1_Load);
   this.groupBox1.ResumeLayout(false);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }
//程序开启,串口初始化
  private void Form1_Load(object sender, System.EventArgs e)
  {
   mycom1.PortNum=iPort;
   mycom1.BaudRate=iRate;
   mycom1.ByteSize=bSize;
   mycom1.Parity=bParity;
   mycom1.StopBits=bStopBits;
   mycom1.ReadTimeout=iTimeout;
   if(this.OpenCom())
    msg.AppendText("串口初始化成功……\r\n");
   else
    msg.AppendText("串口初始化失败!\r\n");
  }
//显示包信息
  public string dis_package(byte[] reb)
  {
   string temp="";
   foreach(byte b in reb)
    temp+=b.ToString("X2")+" ";
   return temp;
  }
//开串口
  public bool OpenCom()
  {
   try
   {
     if (mycom1.Opened)
     {
      mycom1.Close();
      mycom1.Open(); //打开串口
     }
     else
     {
      mycom1.Open();//打开串口
     }
     return true;
   }
   catch(Exception e)
   {
     MessageBox.Show("错误:" + e.Message);
     return false;
   }

  }
//发送按钮
  private void button1_Click(object sender, System.EventArgs e)
  {
   if(t_send.Text=="")
   {MessageBox.Show("发送数据为空!");return;}
   byte[] temp1=mysendb();
   int sendnumb=0;
   try
   {
    sendnumb=mycom1.Write(temp1);
     msg.AppendText("\r\n发送数据("+sendnumb+"):"+dis_package(temp1));
    recb=mycom1.Read(50);
    //if(recb.Length!=0)
     msg.AppendText("\r\n接收到数据包:"+dis_package(recb));
   }
   catch
   {msg.AppendText("\r\n发送失败!");return;}
   
   //OpenCom();
  }
//去掉发送数组中的空格
  public string delspace(string putin)
  {
   string putout="";
   for(int i=0;i<putin.Length;i++)
   {
    if(putin[i]!=' ')
     putout+=putin[i];
   }
   return putout;
  }
//提取数据包
  public byte[] mysendb()
  {
   string temps=delspace(t_send.Text);
   byte[] tempb=new byte[50];
   int j=0;
   for(int i=0;i<temps.Length;i=i+2,j++)
    tempb[j]=Convert.ToByte(temps.Substring(i,2),16);
   byte[] send=new byte[j];
   Array.Copy(tempb,send,j);
   return send;
  }
//清空按钮
  private void button3_Click(object sender, System.EventArgs e)
  {
   t_send.Text=string.Empty;
   msg.Text=string.Empty;
  }

//参数设置
  private void button2_Click(object sender, System.EventArgs e)
  {
    mycom1.PortNum=Convert.ToInt16(t_port.Text); //1,2,3,4
   mycom1.BaudRate=Convert.ToInt16(t_rate.Text); //1200,2400,4800,9600
   mycom1.ByteSize=Convert.ToByte(t_bytesize.Text,10); //8 bits
   mycom1.Parity=Convert.ToByte(t_parity.Text,10); // 0-4=no,odd,even,mark,space
   mycom1.StopBits=Convert.ToByte(t_stopbyte.Text,10); // 0,1,2 = 1, 1.5, 2
   //iTimeout=3;
   if(this.OpenCom())
    msg.AppendText("串口初始化成功……\r\n");
   else
    msg.AppendText("串口初始化失败!\r\n");
  }
//程序关闭,结束串口
  private void Form1_Closing(object sender, e)
  {
   mycom1.Close();
  }

  private void button5_Click(object sender, System.EventArgs e)
  {
   if(mycom1.Opened)
   {
    mycom1.Close();
    button5.Text="开启串口";
    msg.AppendText("\r\n串口被关闭……");
   }
   else
   {
    mycom1.Open();
    button5.Text="关闭串口";
    msg.AppendText("\r\n串口成功开启……");
   }
  }
 }
}
搜索更多相关主题的帖子: using System 邮箱 summary Forms 
2008-01-28 12:53
星之魂
Rank: 1
等 级:新手上路
帖 子:34
专家分:0
注 册:2007-12-28
收藏
得分:0 
应该缺少一些代码吧?我就找不到mycom怎么来的

[[it] 本帖最后由 星之魂 于 2008-1-28 22:46 编辑 [/it]]
2008-01-28 22:30
软件编程
Rank: 1
来 自:北京
等 级:新手上路
帖 子:1
专家分:0
注 册:2008-2-23
收藏
得分:0 
代码不全,缺少了mycom这个类
2008-02-23 13:16
pacocai
Rank: 3Rank: 3
等 级:新手上路
威 望:6
帖 子:1583
专家分:0
注 册:2007-3-12
收藏
得分:0 
最核心的类居然没有………………

浮生若梦天边月,醉死如酒水中星。红楼一梦千人叹,岂让万夫空做贱。博客:http://hi.baidu.com/rxvip
2008-02-23 13:37
pacocai
Rank: 3Rank: 3
等 级:新手上路
威 望:6
帖 子:1583
专家分:0
注 册:2007-3-12
收藏
得分:0 
国外网站一个用C#来操作串口的类。
/*
* Author: Marcus Lorentzon, 2001
*         d98malor@dtek.chalmers.se
*
* Freeware: Please do not remove this header
*
* File: SerialStream.cs
*
* Description: Implements a Stream for asynchronous
*              transfers and COMM. Stream version.
*
* Version: 2.4
*
*/

#region Using

using System;
using
using System.Threading;
using System.Runtime.InteropServices;
using

#endregion Using

namespace {

    public class SerialStream : Stream {
        
        #region Attributes

        private IOCompletionCallback m_IOCompletionCallback;
        private IntPtr m_hFile = IntPtr.Zero;
        private string m_sPort;
        private bool m_bRead;
        private bool m_bWrite;

        #endregion Attributes

        #region Properties

        public string Port {
            get {
                return m_sPort;
            }
            set {
                if (m_sPort != value) {
                    Close();
                    Open(value);
                }
            }
        }

        public override bool CanRead {
            get {
                return m_bRead;
            }
        }

        public override bool CanWrite {
            get {
                return m_bWrite;
            }
        }

        public override bool CanSeek {
            get {
                return false;
            }
        }

        public bool Closed  {
            get {
                return m_hFile.ToInt32()  0;
            }
        }

        public bool Dsr {
            get {
                uint status;
                if (!GetCommModemStatus(m_hFile, out status)) {
                    throw new Win32Exception();
                }
                return (status & MS_DSR_ON) > 0;
            }
        }

        public bool Ring {
            get {
                uint status;
                if (!GetCommModemStatus(m_hFile, out status)) {
                    throw new Win32Exception();
                }
                return (status & MS_RING_ON) > 0;
            }
        }

        public bool Rlsd {
            get {
                uint status;
                if (!GetCommModemStatus(m_hFile, out status)) {
                    throw new Win32Exception();
                }
                return (status & MS_RLSD_ON) > 0;
            }
        }

        #endregion Properties

        #region Constructors

        public SerialStream() : this(FileAccess.ReadWrite) {
        }

        public SerialStream(FileAccess access) {
            m_bRead  = ((int)access & (int)FileAccess.Read) != 0;
            m_bWrite = ((int)access & (int)FileAccess.Write) != 0;
            unsafe {
                m_IOCompletionCallback = new IOCompletionCallback(AsyncFSCallback);
            }
        }

        public SerialStream(string port) : this(FileAccess.ReadWrite) {
            Open(port);
        }

        public SerialStream(string port, FileAccess access) : this(access) {
            Open(port);
        }

        #endregion Constructors

        #region Methods

        public void Open(string port) {
            if (m_hFile != IntPtr.Zero) {
                throw new IOException("Stream already opened.");
            }
            m_sPort = port;
            m_hFile = CreateFile(port, (uint)((m_bRead?GENERIC_READ:0)|(m_bWrite?GENERIC_WRITE:0)), 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
            if (m_hFile.ToInt32() == INVALID_HANDLE_VALUE) {
                m_hFile = IntPtr.Zero;
                throw new FileNotFoundException("Unable to open " + port);
            }

            ThreadPool.BindHandle(m_hFile);

            SetTimeouts(0, 0, 0, 0, 0);
        }

        public override void Close() {
            CloseHandle(m_hFile);
            m_hFile = IntPtr.Zero;
            m_sPort = null;
        }

        public IAsyncResult BeginRead(byte[] buffer) {
            return BeginRead(buffer, 0, buffer.Length, null, null);
        }

        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
            GCHandle gchBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            SerialAsyncResult sar = new SerialAsyncResult(this, state, callback, true, gchBuffer);
            Overlapped ov = new Overlapped(0, 0, sar.AsyncWaitHandle.Handle.ToInt32(), sar);
            unsafe {
                NativeOverlapped* nov = ov.Pack(m_IOCompletionCallback);
                byte* data = (byte*)((int)gchBuffer.AddrOfPinnedObject() + offset);

                uint read = 0;
                if (ReadFile(m_hFile, data, (uint)count, out read, nov)) {
                    sar.m_bCompletedSynchronously = true;
                    return sar;
                }
                else if (GetLastError() == ERROR_IO_PENDING) {
                    return sar;
                }
                else
                    throw new Exception("Unable to initialize read. Errorcode: " + GetLastError().ToString());
            }
        }

        public IAsyncResult BeginWrite(byte[] buffer) {
            return BeginWrite(buffer, 0, buffer.Length, null, null);
        }

        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) {
            GCHandle gchBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
            SerialAsyncResult sar = new SerialAsyncResult(this, state, callback, false, gchBuffer);
            Overlapped ov = new Overlapped(0, 0, sar.AsyncWaitHandle.Handle.ToInt32(), sar);
            unsafe {
                NativeOverlapped* nov = ov.Pack(m_IOCompletionCallback);
                byte* data = (byte*)((int)gchBuffer.AddrOfPinnedObject() + offset);

                uint written = 0;
                if (WriteFile(m_hFile, data, (uint)count, out written, nov)) {
                    sar.m_bCompletedSynchronously = true;
                    return sar;
                }
                else if (GetLastError() == ERROR_IO_PENDING) {
                    return sar;
                }
                else
                    throw new Exception("Unable to initialize write. Errorcode: " + GetLastError().ToString());
            }
        }

        private int EndOperation(IAsyncResult asyncResult, bool isRead) {
            SerialAsyncResult sar = (SerialAsyncResult)asyncResult;
            if (sar.m_bIsRead != isRead)
                throw new IOException("Invalid parameter: IAsyncResult is not from a " + (isRead ? "read" : "write"));
            if (sar.EndOperationCalled) {
                throw new IOException("End" + (isRead ? "Read" : "Write") + " called twice for the same operation.");
            }
            else {
                sar.m_bEndOperationCalled = true;
            }

            while (!sar.m_bCompleted) {
                sar.AsyncWaitHandle.WaitOne();
            }

            sar.Dispose();

            if (sar.m_nErrorCode != ERROR_SUCCESS && sar.m_nErrorCode != ERROR_OPERATION_ABORTED) {
                throw new IOException("Operation finished with errorcode: " + sar.m_nErrorCode);
            }

            return sar.m_nReadWritten;
        }
        
        public override int EndRead(IAsyncResult asyncResult) {
            return EndOperation(asyncResult, true);
        }
        
        public override void EndWrite(IAsyncResult asyncResult) {
            EndOperation(asyncResult, false);
        }

        public int EndWriteEx(IAsyncResult asyncResult) {
            return EndOperation(asyncResult, false);
        }

        public override int Read(byte[] buffer, int offset, int count) {
            return EndRead(BeginRead(buffer, offset, count, null, null));
        }

        public override void Write(byte[] buffer, int offset, int count) {
            EndWrite(BeginWrite(buffer, offset, count, null, null));
        }

        public int WriteEx(byte[] buffer, int offset, int count) {
            return EndWriteEx(BeginWrite(buffer, offset, count, null, null));
        }

        public int Read(byte[] buffer) {
            return EndRead(BeginRead(buffer, 0, buffer.Length, null, null));
        }

        public int Write(byte[] buffer) {
            return EndOperation(BeginWrite(buffer, 0, buffer.Length, null, null), false);
        }

        public override void Flush() {
            FlushFileBuffers(m_hFile);
        }

        public bool PurgeRead() {
            return PurgeComm(m_hFile, PURGE_RXCLEAR);
        }

        public bool PurgeWrite() {
            return PurgeComm(m_hFile, PURGE_TXCLEAR);
        }

        public bool Purge() {
            return PurgeRead() && PurgeWrite();
        }

        public bool CancelRead() {
            return PurgeComm(m_hFile, PURGE_RXABORT);
        }

        public bool CancelWrite() {
            return PurgeComm(m_hFile, PURGE_TXABORT);
        }

        public bool CancelAll() {
            return CancelRead() && CancelWrite();
        }

        public override void SetLength(long nLength) {
            throw new NotSupportedException("SetLength isn't supported on serial ports.");
        }

        public override long Seek(long offset, SeekOrigin origin) {
            throw new NotSupportedException("Seek isn't supported on serial ports.");
        }

        public void SetTimeouts(int ReadIntervalTimeout,
                                int ReadTotalTimeoutMultiplier,
                                int ReadTotalTimeoutConstant,
                                int WriteTotalTimeoutMultiplier,
                                int WriteTotalTimeoutConstant) {
            SerialTimeouts Timeouts = new SerialTimeouts(ReadIntervalTimeout,
                                                         ReadTotalTimeoutMultiplier,
                                                         ReadTotalTimeoutConstant,
                                                         WriteTotalTimeoutMultiplier,
                                                         WriteTotalTimeoutConstant);
            unsafe { SetCommTimeouts(m_hFile, ref Timeouts); }
        }

        public bool SetPortSettings(uint baudrate) {
            return SetPortSettings(baudrate, FlowControl.Hardware);
        }

        public bool SetPortSettings(uint baudrate, FlowControl flowControl) {
            return SetPortSettings(baudrate, flowControl, Parity.None);
        }

        public bool SetPortSettings(uint baudrate, FlowControl flowControl, Parity parity) {
            return SetPortSettings(baudrate, flowControl, parity, 8, StopBits.One);
        }

        public bool SetPortSettings(uint baudrate, FlowControl flowControl, Parity parity, byte databits, StopBits stopbits) {
            unsafe {
                DCB dcb = new DCB();
                dcb.DCBlength = sizeof(DCB);
                dcb.BaudRate = baudrate;
                dcb.ByteSize = databits;
                dcb.StopBits = (byte)stopbits;
                dcb.Parity = (byte)parity;
                dcb.fParity = (parity > 0)? 1U : 0U;
                dcb.fBinary = dcb.fDtrControl = dcb.fTXContinueOnXoff = 1;
                dcb.fOutxCtsFlow = dcb.fAbortOnError = (flowControl == FlowControl.Hardware)? 1U : 0U;
                dcb.fOutX = dcb.fInX = (flowControl == FlowControl.XOnXOff)? 1U : 0U;
                dcb.fRtsControl = (flowControl == FlowControl.Hardware)? 2U : 1U;
                dcb.XonLim = 2048;
                dcb.XoffLim = 512;
                dcb.XonChar = 0x11; // Ctrl-Q
                dcb.XoffChar = 0x13; // Ctrl-S
                return SetCommState(m_hFile, ref dcb);
            }
        }

        public bool SetPortSettings(DCB dcb) {
            return SetCommState(m_hFile, ref dcb);
        }

        public bool GetPortSettings(out DCB dcb) {
            unsafe {
                DCB dcb2 = new DCB();
                dcb2.DCBlength = sizeof(DCB);
                bool ret = GetCommState(m_hFile, ref dcb2);
                dcb = dcb2;
                return ret;
            }
        }

        public bool SetXOn() {
            return EscapeCommFunction(m_hFile, SETXON);
        }

        public bool SetXOff() {
            return EscapeCommFunction(m_hFile, SETXOFF);
        }

        private unsafe void AsyncFSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) {
            SerialAsyncResult sar = (SerialAsyncResult)Overlapped.Unpack(pOverlapped).AsyncResult;

            sar.m_nErrorCode = errorCode;
            sar.m_nReadWritten = (int)numBytes;
            sar.m_bCompleted = true;

            if (sar.Callback != null)
                sar.Callback.Invoke(sar);

            Overlapped.Free(pOverlapped);
        }

        #endregion Methods

        #region Constants

        private const uint PURGE_TXABORT = 0x0001;  // Kill the pending/current writes to the comm port.
        private const uint PURGE_RXABORT = 0x0002;  // Kill the pending/current reads to the comm port.
        private const uint PURGE_TXCLEAR = 0x0004;  // Kill the transmit queue if there.
        private const uint PURGE_RXCLEAR = 0x0008;  // Kill the typeahead buffer if there.

        private const uint SETXOFF  = 1;    // Simulate XOFF received
        private const uint SETXON   = 2;    // Simulate XON received
        private const uint SETRTS    = 3;    // Set RTS high
        private const uint CLRRTS    = 4;    // Set RTS low
        private const uint SETDTR    = 5;    // Set DTR high
        private const uint CLRDTR    = 6;    // Set DTR low
        private const uint SETBREAK    = 8;    // Set the device break line.
        private const uint CLRBREAK    = 9;    // Clear the device break line.

        private const uint MS_CTS_ON  = 0x0010;
        private const uint MS_DSR_ON  = 0x0020;
        private const uint MS_RING_ON = 0x0040;
        private const uint MS_RLSD_ON = 0x0080;

        private const uint FILE_FLAG_OVERLAPPED = 0x40000000;

        private const uint OPEN_EXISTING = 3;

        private const int  INVALID_HANDLE_VALUE = -1;

        private const uint GENERIC_READ = 0x80000000;
        private const uint GENERIC_WRITE = 0x40000000;

        private const uint ERROR_SUCCESS = 0;
        private const uint ERROR_OPERATION_ABORTED = 995;
        private const uint ERROR_IO_PENDING = 997;

        #endregion Constants

        #region Enums

        public enum Parity {None, Odd, Even, Mark, Space};
        public enum StopBits {One, OneAndHalf, Two};
        public enum FlowControl {None, XOnXOff, Hardware};

        #endregion Enums

        #region Classes

        [StructLayout(LayoutKind.Sequential)]
        public struct DCB {

            #region Attributes

            public int DCBlength;
            public uint BaudRate;
            public uint Flags;
            public ushort wReserved;
            public ushort XonLim;
            public ushort XoffLim;
            public byte ByteSize;
            public byte Parity;
            public byte StopBits;
            public sbyte XonChar;
            public sbyte XoffChar;
            public sbyte ErrorChar;
            public sbyte EofChar;
            public sbyte EvtChar;
            public ushort wReserved1;

            #endregion Attributes

            #region Properties

            public uint fBinary { get { return Flags&0x0001; }
                                  set { Flags = Flags & ~1U | value; } }
            public uint fParity { get { return (Flags>>1)&1; }
                                  set { Flags = Flags & ~(1U >2)&1; }
                                  set { Flags = Flags & ~(1U >3)&1; }
                                  set { Flags = Flags & ~(1U >4)&3; }
                                  set { Flags = Flags & ~(3U >6)&1; }
                                  set { Flags = Flags & ~(1U >7)&1; }
                                  set { Flags = Flags & ~(1U >8)&1; }
                                  set { Flags = Flags & ~(1U >9)&1; }
                                  set { Flags = Flags & ~(1U >10)&1; }
                                  set { Flags = Flags & ~(1U >11)&1; }
                                  set { Flags = Flags & ~(1U >12)&3; }
                                  set { Flags = Flags & ~(3U >14)&1; }
                                  set { Flags = Flags & ~(1U << 14) | (value << 14); } }

            #endregion Properties

            #region Methods

            public override string ToString() {
                return "DCBlength: " + DCBlength + "\r\n" +
                    "BaudRate: " + BaudRate + "\r\n" +
                    "fBinary: " + fBinary + "\r\n" +
                    "fParity: " + fParity + "\r\n" +
                    "fOutxCtsFlow: " + fOutxCtsFlow + "\r\n" +
                    "fOutxDsrFlow: " + fOutxDsrFlow + "\r\n" +
                    "fDtrControl: " + fDtrControl + "\r\n" +
                    "fDsrSensitivity: " + fDsrSensitivity + "\r\n" +
                    "fTXContinueOnXoff: " + fTXContinueOnXoff + "\r\n" +
                    "fOutX: " + fOutX + "\r\n" +
                    "fInX: " + fInX + "\r\n" +
                    "fErrorChar: " + fErrorChar + "\r\n" +
                    "fNull: " + fNull + "\r\n" +
                    "fRtsControl: " + fRtsControl + "\r\n" +
                    "fAbortOnError: " + fAbortOnError + "\r\n" +
                    "XonLim: " + XonLim + "\r\n" +
                    "XoffLim: " + XoffLim + "\r\n" +
                    "ByteSize: " + ByteSize + "\r\n" +
                    "Parity: " + Parity + "\r\n" +
                    "StopBits: " + StopBits + "\r\n" +
                    "XonChar: " + XonChar + "\r\n" +
                    "XoffChar: " + XoffChar + "\r\n" +
                    "EofChar: " + EofChar + "\r\n" +
                    "EvtChar: " + EvtChar + "\r\n";
            }

            #endregion Methods
        }

        private class SerialAsyncResult : IAsyncResult, IDisposable {

            #region Attributes

            internal bool m_bEndOperationCalled = false;
            internal bool m_bIsRead;
            internal int m_nReadWritten = 0;
            internal bool m_bCompleted = false;
            internal bool m_bCompletedSynchronously = false;
            internal uint m_nErrorCode = ERROR_SUCCESS;

            private object m_AsyncObject;
            private object m_StateObject;
            private ManualResetEvent m_WaitHandle = new ManualResetEvent(false);
            private AsyncCallback m_Callback;
            private GCHandle m_gchBuffer;

            #endregion Attributes

            #region Properties

            internal bool EndOperationCalled { get { return m_bEndOperationCalled; } }

            public bool IsCompleted { get { return m_bCompleted; } }

            public bool CompletedSynchronously { get { return m_bCompletedSynchronously; } }

            public object AsyncObject { get { return m_AsyncObject; } }

            public object AsyncState { get { return m_StateObject; } }

            public WaitHandle AsyncWaitHandle { get { return m_WaitHandle; } }
            internal ManualResetEvent WaitHandle { get { return m_WaitHandle; } }

            public AsyncCallback Callback { get { return m_Callback; } }

            #endregion Properties

            #region Constructors

            public SerialAsyncResult(object asyncObject,
                object stateObject,
                AsyncCallback callback,
                bool bIsRead,
                GCHandle gchBuffer) {

                m_AsyncObject = asyncObject;
                m_StateObject = stateObject;
                m_Callback = callback;
                m_bIsRead = bIsRead;
                m_gchBuffer = gchBuffer;
            }

            #endregion Constructors

            #region Methods

            public void Dispose() {
                m_WaitHandle.Close();
                m_gchBuffer.Free();
            }

            #endregion Methods
        }

        #endregion Classes

        #region Imports

        [DllImport("kernel32.dll", EntryPoint="CreateFileW",  SetLastError=true,
            CharSet=CharSet.Unicode, ExactSpelling=true)]
        static extern IntPtr CreateFile(string filename, uint access, uint sharemode, uint security_attributes, uint creation, uint flags, uint template);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool CloseHandle(IntPtr handle);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern unsafe bool ReadFile(IntPtr hFile, byte* lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, NativeOverlapped* lpOverlapped);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern unsafe bool WriteFile(IntPtr hFile, byte* lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, NativeOverlapped* lpOverlapped);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool SetCommTimeouts(IntPtr hFile, ref SerialTimeouts lpCommTimeouts);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool SetCommState(IntPtr hFile, ref DCB lpDCB);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool GetCommState(IntPtr hFile, ref DCB lpDCB);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool BuildCommDCB(string def, ref DCB lpDCB);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern int GetLastError();

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool FlushFileBuffers(IntPtr hFile);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool PurgeComm(IntPtr hFile, uint dwFlags);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool EscapeCommFunction(IntPtr hFile, uint dwFunc);

        [DllImport("kernel32.dll", SetLastError=true)]
        static extern bool GetCommModemStatus(IntPtr hFile, out uint modemStat);

        #endregion Imports
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SerialTimeouts {

        #region Attributes

        public int ReadIntervalTimeout;
        public int ReadTotalTimeoutMultiplier;
        public int ReadTotalTimeoutConstant;
        public int WriteTotalTimeoutMultiplier;
        public int WriteTotalTimeoutConstant;

        #endregion Attributes

        #region Constructors

        public SerialTimeouts(int r1, int r2, int r3, int w1, int w2) {
            ReadIntervalTimeout = r1;
            ReadTotalTimeoutMultiplier = r2;
            ReadTotalTimeoutConstant = r3;
            WriteTotalTimeoutMultiplier = w1;
            WriteTotalTimeoutConstant = w2;
        }

        #endregion Constructors

        #region Methods

        public override string ToString() {
            return "ReadIntervalTimeout: " + ReadIntervalTimeout + "\r\n" +
                   "ReadTotalTimeoutMultiplier: " + ReadTotalTimeoutMultiplier + "\r\n" +
                   "ReadTotalTimeoutConstant: " + ReadTotalTimeoutConstant + "\r\n" +
                   "WriteTotalTimeoutMultiplier: " + WriteTotalTimeoutMultiplier + "\r\n" +
                   "WriteTotalTimeoutConstant: " + WriteTotalTimeoutConstant + "\r\n";
        }

        #endregion Methods
    }
}



using System;
using
using System.Threading;

using

namespace SerialStreamReader {

    class App {

        // The main serial stream
        static SerialStream ss;

        [STAThread]
        static void Main(string[] args) {

            // Create a serial port
            ss = new SerialStream();
            try {
                ss.Open("COM4"); //我对猫进行了调用
            }
            catch (Exception e) {
                Console.WriteLine("Error: " + e.Message);
                return;
            }

            // Set port settings
            ss.SetPortSettings(9600);

            // Set timeout so read ends after 20ms of silence after a response
            ss.SetTimeouts(20, 0, 0, 0, 0);

            // Create the StreamWriter used to send commands
            StreamWriter sw = new StreamWriter(ss, System.Text.Encoding.ASCII);

            // Create the Thread used to read responses
            Thread responseReaderThread = new Thread(new ThreadStart(ReadResponseThread));
            responseReaderThread.Start();

            // Read all returned lines
            for (;;) {
                // Read command from console
                string command = Console.ReadLine();

                // Check for exit command
                if (command.Trim().ToLower() == "exit") {
                    responseReaderThread.Abort();
                    break;
                }

                // Write command to modem
                sw.WriteLine(command);
                sw.Flush();
            }
        }

        // Main loop for reading responses
        static void ReadResponseThread() {
            StreamReader sr = new StreamReader(ss, System.Text.Encoding.ASCII);
            try {
                for (;;) {
                    // Read response from modem
                    string response = sr.ReadLine();
                    Console.WriteLine("Response: " + response);
                }
            }
            catch (ThreadAbortException) {
            }
        }
    }
}


程序运行后,你可以对设备进行指令操作。(具体设备接受的指令)

浮生若梦天边月,醉死如酒水中星。红楼一梦千人叹,岂让万夫空做贱。博客:http://hi.baidu.com/rxvip
2008-02-23 13:42
恋轩念伊人
Rank: 5Rank: 5
来 自:湖南衡阳
等 级:贵宾
威 望:19
帖 子:643
专家分:0
注 册:2008-2-23
收藏
得分:0 
疑问
这东西我还真看不明白,只好顶下
2008-02-24 10:39
peach5460
Rank: 15Rank: 15Rank: 15Rank: 15Rank: 15
来 自:武汉
等 级:贵宾
威 望:30
帖 子:2780
专家分:6060
注 册:2008-1-28
收藏
得分:0 
我发现我现在越来越娇嫩了...被VS2005惯坏了...
没语言着色就不想看...呵呵

我总觉得授人以鱼不如授人以渔...
可是总有些SB叫嚣着:要么给代码给答案,要么滚蛋...
虽然我知道不要跟SB一般见识,但是我真的没修炼到宠辱不惊...
2008-02-24 21:12
pacocai
Rank: 3Rank: 3
等 级:新手上路
威 望:6
帖 子:1583
专家分:0
注 册:2007-3-12
收藏
得分:0 
一样……现在没有着色,没有自动完成,没有错误提示。基本不愿看,更不愿写。现在正在反古中……

浮生若梦天边月,醉死如酒水中星。红楼一梦千人叹,岂让万夫空做贱。博客:http://hi.baidu.com/rxvip
2008-02-25 13:10
caifurain
Rank: 1
等 级:新手上路
帖 子:9
专家分:0
注 册:2008-1-28
收藏
得分:0 
顶!
顶!顶上面那个程序!不过看不懂哦
2008-03-01 23:59
caifurain
Rank: 1
等 级:新手上路
帖 子:9
专家分:0
注 册:2008-1-28
收藏
得分:0 
不懂啊!高手救救我
[StructLayout(LayoutKind.Sequential)]  这个什么作用? public struct DCB 结构里的成员为什么没有设置具体值?而是只用int uint byte 等来修饰它们?
在MSDN里我查那些CreateFile函数时它的成员(如lpFileName)本来的修饰符是LPCTSTR ,而在这里为什么是string?根据是什么?
2008-03-02 02:28
快速回复:我下就是这个代码:
数据加载中...
 
   



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

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