ReadDataFromSerialPort.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO.Ports;
  4. using System.Windows.Forms;
  5. namespace UAS_MES_NEW.PublicMethod
  6. {
  7. /// <summary>
  8. /// 从串口获取数据
  9. /// </summary>
  10. class ReadDataFromSerialPort
  11. {
  12. static List<string> OpenPort = new List<string>();
  13. SerialPort serial = new SerialPort();
  14. string SerialPort;
  15. public ReadDataFromSerialPort(string Port)
  16. {
  17. if (!OpenPort.Contains(Port))
  18. {
  19. try
  20. {
  21. SerialPort = Port;
  22. serial.PortName = Port;
  23. OpenPort.Add(Port);
  24. serial.DataReceived += Serial_DataReceived;
  25. serial.Open();
  26. }
  27. catch (Exception ex) { MessageBox.Show(ex.Message); }
  28. }
  29. else
  30. MessageBox.Show(Port + "已开启,请勿重复打开");
  31. }
  32. private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
  33. {
  34. }
  35. /// <summary>
  36. /// 读取串口数据
  37. /// </summary>
  38. /// <returns></returns>
  39. public string Read()
  40. {
  41. string Data = "";
  42. if (serial.IsOpen)
  43. {
  44. try
  45. {
  46. Data = serial.ReadLine();
  47. serial.DiscardInBuffer();
  48. }
  49. catch (Exception e) { MessageBox.Show(e.Message); }
  50. }
  51. return Data;
  52. }
  53. /// <summary>
  54. /// 如果打开的串口不为空则进行关闭
  55. /// </summary>
  56. public void Close()
  57. {
  58. if (serial.IsOpen)
  59. {
  60. serial.Close();
  61. OpenPort.Remove(SerialPort);
  62. }
  63. }
  64. }
  65. }