12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System;
- using System.IO.Ports;
- using System.Text;
- using System.Windows.Forms;
- using System.Windows.Media;
- namespace BarrageTransporter
- {
- class AppContext
- {
- // 数据缓存路径
- public static string TEMPPATH = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- // 串口类
- SerialPort serialPort = null;
- // 打开串口标志位
- public bool portOpen = false;
- private static AppContext appContext;
- private AppContext() { }
- public static AppContext getAppContext()
- {
- if (appContext == null)
- {
- appContext = new AppContext();
- }
- return appContext;
- }
- public SerialPort SerialPort
- {
- set
- {
- if (value == null)
- {
- portOpen = false;
- MainWindow.status.Content = "未连接";
- MainWindow.status.ToolTip = "设备未连接";
- MainWindow.status.Foreground = new SolidColorBrush(Colors.Red);
- }
- else
- {
- portOpen = true;
- MainWindow.status.Content = "已连接";
- MainWindow.status.ToolTip = "设备已连接";
- MainWindow.status.Foreground = new SolidColorBrush(Colors.Green);
- }
- serialPort = value;
- }
- get
- {
- return serialPort;
- }
- }
- public bool PortOpen
- {
- set
- {
- portOpen = value;
- }
- get
- {
- return portOpen;
- }
- }
- public void dataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- try
- {
- // Comm.BytesToRead 中为要读入的字节长度
- int len = serialPort.BytesToRead;
- Byte[] readBuffer = new Byte[len];
- // 将数据读入缓存
- serialPort.Read(readBuffer, 0, len);
- // 处理 readBuffer 中的数据,自定义处理过程
- string msg = Encoding.Default.GetString(readBuffer, 0, len);
- Console.WriteLine(msg);
- }
- catch (Exception ex)
- {
- MessageBox.Show("接收返回消息异常!具体原因:" + ex.Message, "错误提示");
- }
- }
- }
- }
|