最好经过测试的

解决方案 »

  1.   

    我用vs2005的串口控件:
    写:
    private void button1_Click(object sender, EventArgs e)
            {
                if (!sp.IsOpen)
                {
                    if (textBox1.Text != "")
                    {
                        this.sp.Open();
                        byte[] buf = Encoding.ASCII.GetBytes(textBox1.Text.ToString());
                        sp.Write(buf,0,buf.Length);
                        textBox1.Text = "";
                        toolStripStatusLabel1.Text = "发送成功!";
                        sp.Close();
                    }  
                }
            }读:
            byte[] by = new byte[1024];
            private  delegate void SetTexts();
            public ClientForm()
            {
                InitializeComponent();
            }        private void button1_Click(object sender, EventArgs e)
            {
                if (!sp2.IsOpen)
                {
                    sp2.Open();
                }
                
            }        private void sp2_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {            
               
               
                sp2.Read(by, 0, by.Length);           
                this.Invoke(new SetTexts(SetText));
                       
            }
            public void SetText()
            {
                textBox1.Text=null;
                textBox1.Text += Encoding.ASCII.GetString(by);
             }
      

  2.   

    #region Usingusing System;
    using System.IO;
    using System.Threading;
    using System.Runtime.InteropServices;
    using System.ComponentModel;#endregion Usingnamespace LoMaN.IO {    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);
            }
      

  3.   

    net2.0有现成的类SerialPorts超级好用
                   StringBuilder sb = new StringBuilder();
                    sb.Append((char)27);
                    sb.Append((char)118);
                    SerialPort sp = null;
                    int i = -1;
                    try
                    {
                        sp = new SerialPort(sPort);
                        sp.Open();
                        sp.WriteLine(sb.ToString());
                        sp.ReadTimeout = 3000;
                        i = sp.ReadByte();
                        sp.Close();
                    }
                    catch 
                    {
                        if (sp != null) sp.Close();
                        return i;
                    }
                    return i;
    读取热敏打印机状态
      

  4.   

    usepc(usepc) 
    现实:“上下文没有Encoding“????如何处理???
      

  5.   

    要的话给你代码,先给分吧。
    [email protected]
      

  6.   

    ok
    my email [email protected]
      

  7.   

    public class SerialComm
    {
    public int PortNum;
    public int BaudRate;
    public byte ByteSize;
    public byte Parity = 0; // 0-4=no,odd,even,,space 
    public byte StopBits; // 0,1,2 = 1, 1.5, 2 
    public int ReadTimeout; //comm port win32 file handle
    private int hComm = -1;

    public bool Opened = false;
     
    //win32 api constants
    private const uint GENERIC_READ = 0x80000000;
    private const uint GENERIC_WRITE = 0x40000000;
    private const int OPEN_EXISTING = 3;
    private const int INVALID_HANDLE_VALUE = -1;

    [StructLayout(LayoutKind.Sequential)]
    public struct DCB 
    {
    //taken from c struct in platform sdk 
    public int DCBlength;           // sizeof(DCB) 
    public int BaudRate;            // current baud rate
    /* these are the c struct bit fields, bit twiddle flag to set
    public int fBinary;          // binary mode, no EOF check 
    public int fParity;          // enable parity checking 
    public int fOutxCtsFlow;      // CTS output flow control 
    public int fOutxDsrFlow;      // DSR output flow control 
    public int fDtrControl;       // DTR flow control type 
    public int fDsrSensitivity;   // DSR sensitivity 
    public int fTXContinueOnXoff; // XOFF continues Tx 
    public int fOutX;          // XON/XOFF out flow control 
    public int fInX;           // XON/XOFF in flow control 
    public int fErrorChar;     // enable error replacement 
    public int fNull;          // enable null stripping 
    public int fRtsControl;     // RTS flow control 
    public int fAbortOnError;   // abort on error 
    public int fDummy2;        // reserved 
    */
    public uint flags;
    public ushort wReserved;          // not currently used 
    public ushort XonLim;             // transmit XON threshold 
    public ushort XoffLim;            // transmit XOFF threshold 
    public byte ByteSize;           // number of bits/byte, 4-8 
    public byte Parity;             // 0-4=no,odd,even,,space 
    public byte StopBits;           // 0,1,2 = 1, 1.5, 2 
    public char XonChar;            // Tx and Rx XON character 
    public char XoffChar;           // Tx and Rx XOFF character 
    public char ErrorChar;          // error replacement character 
    public char EofChar;            // end of input character 
    public char EvtChar;            // received event character 
    public ushort wReserved1;         // reserved; do not use 
    } [StructLayout(LayoutKind.Sequential)]
    private struct COMMTIMEOUTS 
    {  
    public int ReadIntervalTimeout; 
    public int ReadTotalTimeoutMultiplier; 
    public int ReadTotalTimeoutConstant; 
    public int WriteTotalTimeoutMultiplier; 
    public int WriteTotalTimeoutConstant; 
    }  [StructLayout(LayoutKind.Sequential)]
    private struct OVERLAPPED

    public int  Internal; 
    public int  InternalHigh; 
    public int  Offset; 
    public int  OffsetHigh; 
    public int hEvent; 
    }  

    [DllImport("kernel32.dll")]
    private static extern int CreateFile(
    string lpFileName,                         // file name
    uint dwDesiredAccess,                      // access mode
    int dwShareMode,                          // share mode
    int lpSecurityAttributes, // SD
    int dwCreationDisposition,                // how to create
    int dwFlagsAndAttributes,                 // file attributes
    int hTemplateFile                        // handle to template file
    ); [DllImport("kernel32.dll")]
    private static extern bool GetCommState(
    int hFile,  // handle to communications device
    ref DCB lpDCB    // device-control block
    ); [DllImport("kernel32.dll")]
    private static extern bool BuildCommDCB(
    string lpDef,  // device-control string
    ref DCB lpDCB     // device-control block
    ); [DllImport("kernel32.dll")]
    private static extern bool SetCommState(
    int hFile,  // handle to communications device
    ref DCB lpDCB    // device-control block
    ); [DllImport("kernel32.dll")]
    private static extern bool GetCommTimeouts(
    int hFile,                  // handle to comm device
    ref COMMTIMEOUTS lpCommTimeouts  // time-out values
    ); [DllImport("kernel32.dll")]
    private static extern bool SetCommTimeouts(
    int hFile,                  // handle to comm device
    ref COMMTIMEOUTS lpCommTimeouts  // time-out values
    ); [DllImport("kernel32.dll")]
    private static extern bool ReadFile(
    int hFile,                // handle to file
    byte[] lpBuffer,             // data buffer
    int nNumberOfBytesToRead,  // number of bytes to read
    ref int lpNumberOfBytesRead, // number of bytes read
    ref OVERLAPPED lpOverlapped    // overlapped buffer
    ); [DllImport("kernel32.dll")]
    private static extern bool WriteFile(
    int hFile,                    // handle to file
    byte[] lpBuffer,                // data buffer
    int nNumberOfBytesToWrite,     // number of bytes to write
    ref int lpNumberOfBytesWritten,  // number of bytes written
    ref OVERLAPPED lpOverlapped        // overlapped buffer
    ); [DllImport("kernel32.dll")]
    private static extern bool CloseHandle(
    int hObject   // handle to object
    ); [DllImport("kernel32.dll")]
    private static extern uint GetLastError();

    public void Open()
    {
     
    DCB dcbCommPort = new DCB();
    COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

    // OPEN THE COMM PORT.
    hComm = CreateFile("COM" + PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);

    // IF THE PORT CANNOT BE OPENED, BAIL OUT.
    if(hComm == INVALID_HANDLE_VALUE)
    {
    throw(new ApplicationException("Comm Port Can Not Be Opened"));
    }

    // SET THE COMM TIMEOUTS.
    GetCommTimeouts(hComm,ref ctoCommPort);
    ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
    ctoCommPort.ReadTotalTimeoutMultiplier = 0;
    ctoCommPort.WriteTotalTimeoutMultiplier = 0;
    ctoCommPort.WriteTotalTimeoutConstant = 0;  
    SetCommTimeouts(hComm,ref ctoCommPort);

    // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
    bool ju=GetCommState(hComm, ref dcbCommPort);
    dcbCommPort.BaudRate=BaudRate;
    dcbCommPort.flags=0;
    //dcb.fBinary=1;
    dcbCommPort.flags|=1;
    if (Parity>0)
    {
    //dcb.fParity=1
    dcbCommPort.flags|=2;
    }
       dcbCommPort.Parity=Parity;
       dcbCommPort.ByteSize=ByteSize;
    if(StopBits==1)
    dcbCommPort.StopBits=0;
    if(StopBits==2)
    dcbCommPort.StopBits=2;
     if (!SetCommState(hComm, ref dcbCommPort))
    {
    //uint ErrorNum=GetLastError();
    throw(new ApplicationException("Comm Port Can Not Be Opened"));
    }
    //unre to see if setting took correctly
    //DCB dcbCommPort2 = new DCB();
    //GetCommState(hComm, ref dcbCommPort2);
    Opened = true;
      
    }

    public void Close()
    {
    if (hComm!=INVALID_HANDLE_VALUE)
    {
    CloseHandle(hComm);
    }
    }

    public byte[] Read(int NumBytes)
    {
    byte[] BufBytes;
    byte[] OutBytes;
    BufBytes = new byte[NumBytes]; if (hComm!=INVALID_HANDLE_VALUE)
    {
    OVERLAPPED ovlCommPort = new OVERLAPPED();
    int BytesRead=0;
    ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
    OutBytes = new byte[BytesRead];
    Array.Copy(BufBytes,OutBytes,BytesRead);

    else
    {
    throw(new ApplicationException("Comm Port Not Open"));
    }
    return OutBytes;
    }

    public void Write(byte[] WriteBytes)
    {
    if (hComm!=INVALID_HANDLE_VALUE)
    {
    OVERLAPPED ovlCommPort = new OVERLAPPED();
    int BytesWritten = 0;
    WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
    }
    else
    {
    throw(new ApplicationException("Comm Port Not Open"));
    }
    }
    }