AppContext.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.IO.Ports;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Windows.Media;
  6. namespace BarrageTransporter
  7. {
  8. class AppContext
  9. {
  10. // 数据缓存路径
  11. public static string TEMPPATH = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
  12. // 串口类
  13. SerialPort serialPort = null;
  14. // 打开串口标志位
  15. public bool portOpen = false;
  16. private static AppContext appContext;
  17. private AppContext() { }
  18. public static AppContext getAppContext()
  19. {
  20. if (appContext == null)
  21. {
  22. appContext = new AppContext();
  23. }
  24. return appContext;
  25. }
  26. public SerialPort SerialPort
  27. {
  28. set
  29. {
  30. if (value == null)
  31. {
  32. portOpen = false;
  33. MainWindow.status.Content = "未连接";
  34. MainWindow.status.ToolTip = "设备未连接";
  35. MainWindow.status.Foreground = new SolidColorBrush(Colors.Red);
  36. }
  37. else
  38. {
  39. portOpen = true;
  40. MainWindow.status.Content = "已连接";
  41. MainWindow.status.ToolTip = "设备已连接";
  42. MainWindow.status.Foreground = new SolidColorBrush(Colors.Green);
  43. }
  44. serialPort = value;
  45. }
  46. get
  47. {
  48. return serialPort;
  49. }
  50. }
  51. public bool PortOpen
  52. {
  53. set
  54. {
  55. portOpen = value;
  56. }
  57. get
  58. {
  59. return portOpen;
  60. }
  61. }
  62. public void dataReceived(object sender, SerialDataReceivedEventArgs e)
  63. {
  64. try
  65. {
  66. // Comm.BytesToRead 中为要读入的字节长度
  67. int len = serialPort.BytesToRead;
  68. Byte[] readBuffer = new Byte[len];
  69. // 将数据读入缓存
  70. serialPort.Read(readBuffer, 0, len);
  71. // 处理 readBuffer 中的数据,自定义处理过程
  72. string msg = Encoding.Default.GetString(readBuffer, 0, len);
  73. Console.WriteLine(msg);
  74. }
  75. catch (Exception ex)
  76. {
  77. MessageBox.Show("接收返回消息异常!具体原因:" + ex.Message, "错误提示");
  78. }
  79. }
  80. }
  81. }