using Microsoft.Win32; using System; using System.IO; using System.IO.Ports; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; using 优软MES.CustomControl; namespace 优软MES { public partial class Weigher : Form { [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); public const int WM_SYSCOMMAND = 0x0112; public const int SC_MOVE = 0xF010; public const int HTCAPTION = 0x0002; string LastData=""; //实例化一个串口 SerialPort serialPort1 = new SerialPort(); Thread thread; bool getData; public Weigher() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; GetComList(); } private void Weigher_Load(object sender, EventArgs e) { this.headBar1.MouseDown += new MouseEventHandler(headBar_MouseDown); } private void GetSeriadlData_Click(object sender, EventArgs e) { getData = true; thread = new Thread(getSerialData); thread.Start(); } private void StopGetSeriadlData_Click(object sender, EventArgs e) { getData = false; Thread.Sleep(1000); serialPort1.Close(); } //开始接受串口数据 private void getSerialData(){ if (!serialPort1.IsOpen) { serialPort1.PortName = this.comboBox1.Text; serialPort1.BaudRate =int.Parse(BaudRate.Text); serialPort1.Open(); DataFlush.Text = "开始接受数据\n"; while (getData) { try { ShowData(serialPort1.ReadLine() + "\n"); } catch (IOException ex) { MessageBox.Show(ex.Message); } } } else { MessageBox.Show("请勿重复打开端口", "警告"); } } // 获取串口列表 private void GetComList() { RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm"); if (keyCom != null) { string[] sSubKeys = keyCom.GetValueNames(); //获取串口的名称 //for (int i = 0; i < sSubKeys.Length; i++) //{ // string sValue = (string)(sSubKeys[i]); // comboBox1.Items.Add(sValue); // comboBox1.SelectedIndex = i; //} //获取串口号 for (int i = 0; i < sSubKeys.Length; i++) { string sValue = (string)keyCom.GetValue(sSubKeys[i]); comboBox1.Items.Add(sValue); comboBox1.SelectedIndex = i; } } } private void headBar_MouseDown(object sender, MouseEventArgs e) { ReleaseCapture(); SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); } private void ShowData(string Data) { //判断数据是否稳定,将稳定值展示到称量结果 if (Data.Substring(0, 1) == "S") { WeigherData.Text = Data; } //判断数据和上一条是否相等 if (!(LastData == Data)) { DataFlush.AppendText(Data); } LastData = Data; } private void Weigher_FormClosing(object sender, FormClosingEventArgs e) { if (serialPort1.IsOpen) { MessageBoxButtons messButton = MessageBoxButtons.YesNo; string logout_confirm = MessageBox.Show(this.ParentForm, "端口尚未关闭,仍要关闭窗口?", "警告!", messButton).ToString(); if (!(logout_confirm == "Yes")) { e.Cancel = true; } } } } }