ReadDataFromSerialPort.cs 1.9 KB

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