C#串口通信编程类(修改版)(2)


   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.
   // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
   // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
   // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
   // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.
 
   dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
   GetCommState(hComm, ref dcbCommPort);
   dcbCommPort.BaudRate=BaudRate;
   dcbCommPort.Parity=Parity;
   dcbCommPort.ByteSize=ByteSize;
   dcbCommPort.StopBits=StopBits;
   SetCommState(hComm, ref dcbCommPort);
   
   Opened = true;
   
  }
 
  public void Close()
  {
   if (hComm!=INVALID_HANDLE_VALUE)
   {
    CloseHandle(hComm);
                Opened=false;
   }
  }
 
  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 int Write(byte[] WriteBytes)
  {
   int BytesWritten = 0;
   if (hComm!=INVALID_HANDLE_VALUE)
   {
    OVERLAPPED ovlCommPort = new OVERLAPPED();
    WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
   }
   else
   {
    throw(new ApplicationException("Comm Port Not Open"));
   } 
   return BytesWritten;
  }
 }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://127.0.0.1/wyyxdw.html