ReadDataFromSerialPort.cs 1.8 KB

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