http://www.codeproject.com/dotnet/DotNetComPorts.asp

解决方案 »

  1.   

    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;namespace RS232Test
    {
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.RichTextBox richTextBoxReceive;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox textBoxSend;
    private System.Windows.Forms.Button buttonSend;
    private AxMSCommLib.AxMSComm axMSComm1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null; public Form1()
    {
    //
    // Required for Windows Form Designer support
    //
    InitializeComponent();
    InitComPort(); //
    // TODO: Add any constructor code after InitializeComponent call
    //
    }
    private void InitComPort()
    {
    // 设置端Com2
    this.axMSComm1.CommPort = 2;
        
    // 检查一下COM1是否使用了,若被使用了,把Com1关闭并从职.
    if (this.axMSComm1.PortOpen) 
    this.axMSComm1.PortOpen = false;
        
    // 设置当有数据进入缓冲区出发OnComm事件
    this.axMSComm1.RThreshold = 1;  
        
    // 初始化设置
    this.axMSComm1.Settings = "9600,n,8,1"; //强制DTR线路为高电位(一般用不上)
    this.axMSComm1.DTREnable = true;
        
    // 不使用握手协议(一般用不上)
    this.axMSComm1.Handshaking = MSCommLib.HandshakeConstants.comNone; // 使用文字传输模式
    this.axMSComm1.InputMode = MSCommLib.InputModeConstants.comInputModeText;
        
       
    // 使用Input时为读取全部数据
    this.axMSComm1.InputLen = 0; // 0x00为有效字节
    this.axMSComm1.NullDiscard = false; //注册OnComm的时间处理函数

    this.axMSComm1.OnComm += new System.EventHandler(this.axMSComm1_OnComm);// 註冊注册OnComm的事件處理函式
        
    // 打开COM1
    this.axMSComm1.PortOpen = true;  
    }
    /*private void OnComm(object sender, EventArgs e)  //  MSCommLib OnComm Event Handler
    {
    //檢查緩衝區裏是否有資料,若有資料將資料傳給ProcessComData處理,當然您也可以直接在
    //這個函式中處理,在此我們將資料轉字串的方式處理(string),若是其他的資料,則轉為byte矩陣(byte [])。
    if (this.axMSComm1.InBufferCount > 0) 
    ProcessComData((string) this.axMSComm1.Input);
    }*/ private void ProcessComData(string input)
    {
       
    this.richTextBoxReceive.AppendText(input + "\n");
    } /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
    this.richTextBoxReceive = new System.Windows.Forms.RichTextBox();
    this.label1 = new System.Windows.Forms.Label();
    this.textBoxSend = new System.Windows.Forms.TextBox();
    this.buttonSend = new System.Windows.Forms.Button();
    this.axMSComm1 = new AxMSCommLib.AxMSComm();
    ((System.ComponentModel.ISupportInitialize)(this.axMSComm1)).BeginInit();
    this.SuspendLayout();
    // 
    // richTextBoxReceive
    // 
    this.richTextBoxReceive.Location = new System.Drawing.Point(29, 30);
    this.richTextBoxReceive.Name = "richTextBoxReceive";
    this.richTextBoxReceive.Size = new System.Drawing.Size(461, 194);
    this.richTextBoxReceive.TabIndex = 0;
    this.richTextBoxReceive.Text = "";
    // 
    // label1
    // 
    this.label1.Location = new System.Drawing.Point(29, 7);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(182, 15);
    this.label1.TabIndex = 1;
    this.label1.Text = "所接受信息:";
    // 
    // textBoxSend
    // 
    this.textBoxSend.Location = new System.Drawing.Point(29, 246);
    this.textBoxSend.Name = "textBoxSend";
    this.textBoxSend.Size = new System.Drawing.Size(374, 21);
    this.textBoxSend.TabIndex = 2;
    this.textBoxSend.Text = "Let\'s go go go";
    // 
    // buttonSend
    // 
    this.buttonSend.Location = new System.Drawing.Point(413, 246);
    this.buttonSend.Name = "buttonSend";
    this.buttonSend.Size = new System.Drawing.Size(86, 23);
    this.buttonSend.TabIndex = 3;
    this.buttonSend.Text = "发送";
    this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);
    // 
    // axMSComm1
    // 
    this.axMSComm1.Enabled = true;
    this.axMSComm1.Location = new System.Drawing.Point(8, 80);
    this.axMSComm1.Name = "axMSComm1";
    this.axMSComm1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMSComm1.OcxState")));
    this.axMSComm1.Size = new System.Drawing.Size(38, 38);
    this.axMSComm1.TabIndex = 4;
    this.axMSComm1.OnComm += new System.EventHandler(this.axMSComm1_OnComm);
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(512, 295);
    this.Controls.Add(this.axMSComm1);
    this.Controls.Add(this.buttonSend);
    this.Controls.Add(this.textBoxSend);
    this.Controls.Add(this.label1);
    this.Controls.Add(this.richTextBoxReceive);
    this.Name = "Form1";
    this.Text = "Form1";
    this.Load += new System.EventHandler(this.Form1_Load);
    ((System.ComponentModel.ISupportInitialize)(this.axMSComm1)).EndInit();
    this.ResumeLayout(false); }
      

  2.   

    #endregion /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    } private void buttonSend_Click(object sender, System.EventArgs e)
    {
    this.axMSComm1.Output=this.textBoxSend.Text;
    } private void axMSComm1_OnComm(object sender, System.EventArgs e)
    {
    if (this.axMSComm1.InBufferCount > 0) 
    ProcessComData((string) this.axMSComm1.Input);
    }
    public short FindDevicePort()
    {
    bool PortOkay = true; 
    short TestPort = 0;    
    bool found = false;  // 檢查所連接的裝置是否有回應(在此假設會回應Hi There)    
    // 不觸發OnComm事件    
    axMSComm1.RThreshold = 0;    // 檢查目前序列埠是否開始,若開啟將其關閉   
    if (axMSComm1.PortOpen)
    axMSComm1.PortOpen = false;    
    do    {        
    TestPort++;  // 試下一個序列埠,本例測試Com1至Com4        
    PortOkay = true;                
    //試著存取TestPort所代表的這個序列埠(電腦上可能會沒這個序列埠^^)       
    try 
    {
    axMSComm1.CommPort = TestPort;
    }        
    catch (System.Runtime.InteropServices.COMException)       
    {
    PortOkay = false;
    }                
    if (PortOkay)  //如果序列埠存在okay的話        
    {            // 試著開啟序列埠(因為有可能會有其他程式開了呀^^)            
    try 
    {
    axMSComm1.PortOpen = true;
    }           
    catch (System.Runtime.InteropServices.COMException)            
    {
    PortOkay = false;
    }
    if (PortOkay) // 如果這時序列埠也是okay的(電腦上有並且沒被使用)           
    {                axMSComm1.Output = "Hello?";
    //送出個字串                
    long TimeStamp = DateTime.Now.Ticks;
    //記得上面提到的跳離迴圈的機制嗎^^在這個例子中使用0.2秒來控制                
    string buffer = "";                
    bool ElapsedTime;                
    do                {                    //這是讓程式也能處理其他的訊息,別當住了.                    System.Windows.Forms.Application.DoEvents();                                        //如果緩衝區內有資料,將資料放至buffer變數內                    if (com.InBufferCount > 0) buffer += com.Input;
    // 看連接的裝置是不是有傳回Hi There^^.                    
    found = (buffer.IndexOf("Hi There") > -1);  
    // 看0.2秒到了沒^^                   
    ElapsedTime = DateTime.Now.Ticks - TimeStamp >                              
    TimeSpan.TicksPerSecond * 0.2;
    // 迴圈一直執行,直到0.2秒到或者連接裝置有傳回Hi There              

    while (!ElapsedTime & !found);           
    }        
    }    

    while ((TestPort < 4) & !found);
    // 傳回連接裝置所連接的序列埠    
    if (found) return TestPort;        // 沒連接裝置囉^^    
    return 0;
    }
    private void Form1_Load(object sender, System.EventArgs e)
    {

    }
    }
    }
      

  3.   

    建议你下载这个用:这个不涉及版权问题,而且做得不错,考虑了许多。
    http://msdn.microsoft.com/msdnmag/issues/02/10/NETSerialComm/default.aspx
      

  4.   

    AxMSCommLib是哪里来的             private AxMSCommLib.AxMSComm axMSComm1;//using System.ComponentModel;
      

  5.   

    到www.GotDotNet.com上搜索SerialPort,你会找到一个很好的串口开发包,有源代码!