using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Ports; using System.Threading; using Newtonsoft.Json.Linq; using Ini; namespace DGPosPay.Window { public partial class WaitWindow : Form { Thread th; IniFile ini = new IniFile(); public string label3data = ""; public int countDownTime = 60; public string posData = ""; public string outstring = ""; private SerialPort serialPort = new SerialPort(); public WaitWindow(SerialPort SerialPort) { InitializeComponent(); countDownTime = int.Parse(ini.IniReadValue("Config", "waitTime")); this.label1.Text = "请操作POS,正在等待POS 返回....."; // 获取当前屏幕的工作区域 Rectangle screenRectangle = Screen.GetWorkingArea(this); // 计算窗体居中的位置 int left = screenRectangle.Left + (screenRectangle.Width - this.Width) / 2; int top = screenRectangle.Top + (screenRectangle.Height - this.Height) / 2; // 设置窗体的位置 this.Location = new Point(left, top); serialPort = SerialPort; if (th == null || !th.IsAlive) { th = new Thread(Run); th.IsBackground = true; th.Start(); } } private void Run() { string errorCode = "-1"; string errorMessage = ""; JObject jObject = new JObject(); int warningTime = int.Parse(ini.IniReadValue("Config", "warningTime")); try { Thread.Sleep(1000); this.Invoke((MethodInvoker)delegate { this.TopMost = false; this.BringToFront(); this.TopMost = true; }); System.Timers.Timer timer = new System.Timers.Timer(1000); timer.Elapsed += (sender, e) => { if (countDownTime > 0) { countDownTime--; if (countDownTime < warningTime) { this.Invoke((MethodInvoker)delegate { this.label2.ForeColor = Color.Red; }); } if (posData == "") { if (serialPort.BytesToRead > 0) { string receivedData = serialPort.ReadExisting(); posData = receivedData; countDownTime = warningTime; JObject posDataobj = JObject.Parse(posData); JObject jObject2 = new JObject(); string status = posDataobj["status"].ToString(); errorMessage = posDataobj["message"].ToString(); this.Invoke((MethodInvoker)delegate { this.label3.Text = errorMessage; }); if (status == "100") { errorCode = "0"; countDownTime = 0; } else { errorCode = status; } jObject2.Add("errorCode", errorCode); jObject2.Add("errorMessage", errorMessage); jObject2.Add("posData", receivedData); outstring = jObject2.ToString(); } } else { if (errorMessage != "") { this.Invoke((MethodInvoker)delegate { this.label3.Text = errorMessage; }); } this.Invoke((MethodInvoker)delegate { this.label2.Text = countDownTime + ""; }); } } else { timer.Stop(); this.Invoke((MethodInvoker)delegate { this.Close(); }); } }; timer.Start(); } catch (Exception ex2) { errorCode = "-1"; errorMessage = ex2.Message; JObject jObject2 = new JObject(); jObject2.Add("errorCode", errorCode); jObject2.Add("errorMessage", errorMessage); outstring = jObject2.ToString(); } } } }