|
@@ -3,14 +3,17 @@ using System.Collections.Generic;
|
|
|
using System.IO.Ports;
|
|
|
using System.Linq;
|
|
|
using System.Text;
|
|
|
+using System.Threading;
|
|
|
using System.Windows.Forms;
|
|
|
using System.Windows.Media;
|
|
|
using System.Windows.Media.Imaging;
|
|
|
+using MessageBox = System.Windows.Forms.MessageBox;
|
|
|
|
|
|
namespace FaceChange
|
|
|
{
|
|
|
internal class AppContext
|
|
|
{
|
|
|
+ private SynchronizationContext _synchronizationContext;
|
|
|
|
|
|
private SerialPort _serialPort;
|
|
|
|
|
@@ -22,7 +25,14 @@ namespace FaceChange
|
|
|
|
|
|
public static AppContext GetAppContext()
|
|
|
{
|
|
|
- return _appContext ?? (_appContext = new AppContext());
|
|
|
+ if (_appContext == null)
|
|
|
+ {
|
|
|
+ _appContext = new AppContext();
|
|
|
+ _appContext._faces = _appContext.FaceInfos;
|
|
|
+
|
|
|
+ _appContext._synchronizationContext = SynchronizationContext.Current;
|
|
|
+ }
|
|
|
+ return _appContext;
|
|
|
}
|
|
|
|
|
|
public SerialPort SerialPort
|
|
@@ -87,6 +97,23 @@ namespace FaceChange
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ private int _lastIndex = -1;
|
|
|
+ private int GetNoRepeatRandom(int min, int max)
|
|
|
+ {
|
|
|
+ if (max - min <= 1)
|
|
|
+ {
|
|
|
+ return min;
|
|
|
+ }
|
|
|
+ var r = new Random();
|
|
|
+ var i = r.Next(min, max);
|
|
|
+ while (i == _lastIndex)
|
|
|
+ {
|
|
|
+ i = r.Next(min, max);
|
|
|
+ }
|
|
|
+ _lastIndex = i;
|
|
|
+ return i;
|
|
|
+ }
|
|
|
+
|
|
|
public void DataReceived(object sender, SerialDataReceivedEventArgs e)
|
|
|
{
|
|
|
try
|
|
@@ -99,11 +126,33 @@ namespace FaceChange
|
|
|
|
|
|
var msg = Encoding.Default.GetString(readBuffer, 0, len);
|
|
|
Console.WriteLine(msg);
|
|
|
+
|
|
|
+ var index = GetNoRepeatRandom(0, _faces.Count);
|
|
|
+ ThreadProcSafePost(index);
|
|
|
}
|
|
|
catch (Exception ex)
|
|
|
{
|
|
|
MessageBox.Show("接收数据异常!具体原因:" + ex.Message, "错误提示");
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ private void ThreadProcSafePost(int text)
|
|
|
+ {
|
|
|
+ _synchronizationContext.Post(SetTextSafePost, text);
|
|
|
+ }
|
|
|
+
|
|
|
+ private void SetTextSafePost(object index)
|
|
|
+ {
|
|
|
+ if (_faces.Count == 0)
|
|
|
+ {
|
|
|
+ MessageBox.Show("请先在设置页添加资源", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ MainWindow.FaceName.Content = _faces[(int)index].Name;
|
|
|
+ MainWindow.FaceSrc.Source = _faces[(int)index].Face;
|
|
|
+ Console.WriteLine(index);
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
}
|