Prechádzať zdrojové kódy

1.完善主窗口逻辑;
2.完善设置窗口逻辑。

Yumin 6 rokov pred
rodič
commit
1db9370712

+ 10 - 22
FaceChange/AppContext.cs

@@ -9,12 +9,10 @@ using System.Windows.Media.Imaging;
 
 namespace FaceChange
 {
-    class AppContext
+    internal class AppContext
     {
         // 串口类
-        private SerialPort _serialPort = null;
-        // 打开串口标志位
-        public bool portOpen = false;
+        private SerialPort _serialPort;
         // Data
         private List<FaceInfo> _faces = new List<FaceInfo>();
 
@@ -33,14 +31,14 @@ namespace FaceChange
             {
                 if (value == null)
                 {
-                    portOpen = false;
+                    PortOpen = false;
                     MainWindow.Status.Content = "未连接";
                     MainWindow.Status.ToolTip = "设备未连接";
                     MainWindow.Status.Foreground = new SolidColorBrush(Colors.Red);
                 }
                 else
                 {
-                    portOpen = true;
+                    PortOpen = true;
                     MainWindow.Status.Content = "已连接";
                     MainWindow.Status.ToolTip = "设备已连接";
                     MainWindow.Status.Foreground = new SolidColorBrush(Colors.Green);
@@ -53,17 +51,8 @@ namespace FaceChange
             }
         }
 
-        public bool PortOpen
-        {
-            set
-            {
-                portOpen = value;
-            }
-            get
-            {
-                return portOpen;
-            }
-        }
+        // 打开串口标志位
+        public bool PortOpen { set; get; }
 
         public List<FaceInfo> FaceInfos
         {
@@ -94,7 +83,6 @@ namespace FaceChange
                         Console.WriteLine(exception);
                     }
                 }
-                Console.WriteLine("123");
                 return _faces;
             }
         }
@@ -104,17 +92,17 @@ namespace FaceChange
             try
             {
                 // Comm.BytesToRead 中为要读入的字节长度
-                int len = _serialPort.BytesToRead;
-                Byte[] readBuffer = new Byte[len];
+                var len = _serialPort.BytesToRead;
+                var readBuffer = new byte[len];
                 // 将数据读入缓存
                 _serialPort.Read(readBuffer, 0, len);
                 // 处理 readBuffer 中的数据,自定义处理过程
-                string msg = Encoding.Default.GetString(readBuffer, 0, len);
+                var msg = Encoding.Default.GetString(readBuffer, 0, len);
                 Console.WriteLine(msg);
             }
             catch (Exception ex)
             {
-                MessageBox.Show("接收返回消息异常!具体原因:" + ex.Message, "错误提示");
+                MessageBox.Show("接收数据异常!具体原因:" + ex.Message, "错误提示");
             }
         }
     }

+ 73 - 9
FaceChange/MainWindow.xaml.cs

@@ -3,6 +3,7 @@ using System.Windows.Input;
 using System.Windows.Controls;
 using System;
 using System.Collections.Generic;
+using System.Windows.Interop;
 
 namespace FaceChange
 {
@@ -11,10 +12,11 @@ namespace FaceChange
     /// </summary>
     public partial class MainWindow : Window
     {
-        AppContext appContext = AppContext.GetAppContext();
-        SerialTool serialTool = SerialTool.GetSerialTool();
+        private readonly AppContext _appContext = AppContext.GetAppContext();
+        private readonly SerialTool _serialTool = SerialTool.GetSerialTool();
 
-        private List<FaceInfo> faces;
+        private readonly List<FaceInfo> _faces;
+        private bool _noDevice;
 
         public static Label Status;
 
@@ -22,12 +24,16 @@ namespace FaceChange
         {
             InitializeComponent();
 
-            faces = appContext.FaceInfos;
+            _faces = _appContext.FaceInfos;
+            Status = PortStatus;
+            LoadDevice();
         }
 
         private void Window_Loaded(object sender, RoutedEventArgs e)
         {
-            Status = PortStatus;
+            // 监听 Windows 消息,获取窗口句柄一定要写在窗口 loaded 事件里,才能获取到窗口句柄,否则为空
+            // 窗口过程 - 挂钩
+            (PresentationSource.FromVisual(this) as HwndSource)?.AddHook(DeviceChanged);
         }
 
         private void Window_KeyDown(object sender, KeyEventArgs e)
@@ -41,15 +47,15 @@ namespace FaceChange
             }
             if (e.Key == Key.Space)
             {
-                if (faces.Count == 0)
+                if (_faces.Count == 0)
                 {
                     MessageBox.Show("请先在设置页添加资源", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                 }
                 else
                 {
-                    var index = GetNoRepeatRandom(0, faces.Count);
-                    Name.Content = faces[index].Name;
-                    Face.Source = faces[index].Face;
+                    var index = GetNoRepeatRandom(0, _faces.Count);
+                    Name.Content = _faces[index].Name;
+                    Face.Source = _faces[index].Face;
                     Console.WriteLine(index);
                 }
             }
@@ -74,6 +80,7 @@ namespace FaceChange
 
         private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
         {
+            if (_noDevice) return;
             var messageBoxResult = MessageBox.Show("确定退出吗?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
             if (messageBoxResult == MessageBoxResult.Cancel)
             {
@@ -98,5 +105,62 @@ namespace FaceChange
             this.WindowStyle = WindowStyle.None;
             this.WindowState = WindowState.Maximized;
         }
+
+        private void LoadDevice()
+        {
+            var portList = _serialTool.FindPort();
+            MessageBoxResult mbr;
+            switch (portList.Count)
+            {
+                case 0:
+                    mbr = MessageBox.Show("没有找到可用硬件!\n请确保连接硬件后再打开本软件。", "错误提示", MessageBoxButton.OK, MessageBoxImage.Warning);
+                    if (mbr == MessageBoxResult.OK)
+                    {
+                        _noDevice = true;
+                        Close();
+                    }
+                    break;
+                case 1:
+                    var serialPort = _serialTool.OpenPort(portList[0], "9600", "8", "1", "无", _appContext.DataReceived);
+                    if (serialPort != null)
+                    {
+                        _appContext.SerialPort = serialPort;
+                    }
+                    break;
+                default:
+                    mbr = MessageBox.Show("请到设置页面配置正确串口!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
+                    if (mbr == MessageBoxResult.OK)
+                    {
+                        
+                    }
+                    break;
+            }
+        }
+
+        // Windows 消息编号,采用 Windows 的消息机制来捕获插入的 USB 状态
+        public const int WmDeviceChange = 0x219;
+        public const int DbtDeviceArrival = 0x8000;
+        public const int DbtDeviceRemoveComplete = 0x8004;
+
+        // 设备插拔改变函数
+        private IntPtr DeviceChanged(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
+        {
+            if (msg == WmDeviceChange)
+            {
+                switch (wParam.ToInt32())
+                {
+                    case DbtDeviceArrival:
+                        // 设备插入
+                        LoadDevice();
+                        Console.WriteLine("设备插入");
+                        break;
+                    case DbtDeviceRemoveComplete:
+                        // 设备卸载
+                        Console.WriteLine("设备卸载");
+                        break;
+                }
+            }
+            return IntPtr.Zero;
+        }
     }
 }

+ 3 - 3
FaceChange/SettingsWindow.xaml

@@ -27,14 +27,14 @@
                     </ComboBox.RenderTransform>
                 </ComboBox>
                 <Button x:Name="Scan" Content="扫描设备" Margin="299,0,0,0" Width="64" Height="24" HorizontalAlignment="Left" Background="White" Foreground="Blue" Click="Scan_Click"/>
-                <Button x:Name="Connect" Content="连接设备" Margin="368,0,0,0" Width="64" Height="24" HorizontalAlignment="Left" Foreground="Lime" Background="White" Click="Connect_Click"/>
+                <Button x:Name="Connect" Content="连接设备" Margin="368,0,0,0" Width="64" Height="24" HorizontalAlignment="Left" Foreground="Green" Background="White" Click="Connect_Click"/>
             </Grid>
         </GroupBox>
         <GroupBox Header="脸谱列表" Margin="10,82,10,10">
             <Grid Margin="10,10,10,10">
                 <Button x:Name="Delete" Content="删除" HorizontalAlignment="Left" Margin="385,245,0,0" VerticalAlignment="Top" Width="47" Height="24" Background="White" Foreground="Red" Click="Delete_Click"/>
-                <Button x:Name="DeleteALL" Content="清空" HorizontalAlignment="Left" Margin="385,274,0,0" VerticalAlignment="Top" Width="47" Height="24" Background="White" Foreground="Red" Click="DeleteALL_Click"/>
-                <Button x:Name="Add" Content="添加" HorizontalAlignment="Left" Margin="385,303,0,0" VerticalAlignment="Top" Width="47" Height="24" Background="White" Foreground="Lime" Click="Add_Click"/>
+                <Button x:Name="DeleteAll" Content="清空" HorizontalAlignment="Left" Margin="385,274,0,0" VerticalAlignment="Top" Width="47" Height="24" Background="White" Foreground="Red" Click="DeleteAll_Click"/>
+                <Button x:Name="Add" Content="添加" HorizontalAlignment="Left" Margin="385,303,0,0" VerticalAlignment="Top" Width="47" Height="24" Background="White" Foreground="Green" Click="Add_Click"/>
                 <ListBox x:Name="ListBox" ItemsSource="{Binding}" Grid.Column="2" Margin="0,0,62,0">
                     <ListBox.ItemTemplate>
                         <DataTemplate>

+ 11 - 7
FaceChange/SettingsWindow.xaml.cs

@@ -3,10 +3,10 @@ using System.Collections.Generic;
 using System.Drawing;
 using System.Drawing.Imaging;
 using System.IO;
-using System.IO.Ports;
 using System.Windows;
 using System.Windows.Forms;
 using System.Windows.Media.Imaging;
+using Brushes = System.Windows.Media.Brushes;
 
 namespace FaceChange
 {
@@ -15,10 +15,10 @@ namespace FaceChange
     /// </summary>
     public partial class SettingsWindow : Window
     {
-        readonly AppContext _appContext = AppContext.GetAppContext();
-        readonly SerialTool _serialTool = SerialTool.GetSerialTool();
+        private readonly AppContext _appContext = AppContext.GetAppContext();
+        private readonly SerialTool _serialTool = SerialTool.GetSerialTool();
 
-        private List<FaceInfo> _faces;
+        private readonly List<FaceInfo> _faces;
 
         public SettingsWindow()
         {
@@ -36,11 +36,13 @@ namespace FaceChange
                 Devices.SelectedIndex = 0;
                 Devices.IsEnabled = false;
                 Connect.Content = "断开连接";
+                Connect.Foreground = Brushes.Red;
                 Scan.IsEnabled = false;
             }
             else
             {
                 Connect.Content = "连接设备";
+                Connect.Foreground = Brushes.Green;
                 Scan_Click(null, null);
             }
             foreach (var face in _faces)
@@ -109,6 +111,7 @@ namespace FaceChange
                     Scan.IsEnabled = true;
                     Scan_Click(null, null);
                     Connect.Content = "连接设备";
+                    Connect.Foreground = Brushes.Green;
                     _appContext.SerialPort = null;
                 }
                 else
@@ -119,14 +122,14 @@ namespace FaceChange
             else
             {
                 // 检测串口设置
-                string portName = Devices.Text.Trim();
+                var portName = Devices.Text.Trim();
                 if (portName == "")
                 {
                     System.Windows.Forms.MessageBox.Show("没有发现可连接设备!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     return;
                 }
                 // 打开串口
-                SerialPort serialPort = _serialTool.OpenPort(portName, "9600", "8", "1", "无", _appContext.DataReceived);
+                var serialPort = _serialTool.OpenPort(portName, "9600", "8", "1", "无", _appContext.DataReceived);
                 if (serialPort == null)
                 {
                     // 打开串口失败
@@ -137,6 +140,7 @@ namespace FaceChange
                     Devices.IsEnabled = false;
                     Scan.IsEnabled = false;
                     Connect.Content = "断开连接";
+                    Connect.Foreground = Brushes.Red;;
                     _appContext.SerialPort = serialPort;
                 }
             }
@@ -155,7 +159,7 @@ namespace FaceChange
             FaceCount.Content = ListBox.Items.Count.ToString();
         }
 
-        private void DeleteALL_Click(object sender, RoutedEventArgs e)
+        private void DeleteAll_Click(object sender, RoutedEventArgs e)
         {
             var messageBoxButtons = MessageBoxButtons.OKCancel;
             var dr = System.Windows.Forms.MessageBox.Show("将清空列表,确定吗?", "提示", messageBoxButtons, MessageBoxIcon.Warning);