using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Collections; using System.Threading; using System.Timers; using System.Xml; using System.Runtime.InteropServices; using System.Data.SqlClient; using System.Configuration; namespace 串口通信 { public partial class Form1 : Form { public bool isFirstTimeToStart = true; private int timeStamp = 50; public Form1() { InitializeComponent(); } /// <summary> /// 初始化串口属性 /// </summary> public void InitializeSerialPort() { if (isFirstTimeToStart == true) { port.DataBits = 8; port.PortName = this.comboBox1.SelectedItem.ToString(); port.BaudRate = 19200; port.DiscardNull = false; port.DtrEnable = false; port.Handshake = Handshake.None; port.Parity = Parity.None; port.ParityReplace = Convert.ToByte("63"); port.RtsEnable = false; port.StopBits = StopBits.One; isFirstTimeToStart = false; } } private void comboBox1_DropDown(object sender, EventArgs e) { ///加载计算机上所有的COM串口 comboBox1.Items.Clear(); string[] ports = SerialPort.GetPortNames(); foreach (string p in ports) { comboBox1.Items.Add(p); } } //打开串口 private void button1_Click(object sender, EventArgs e) { InitializeSerialPort(); port.Open(); port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); } //执行串口方法 void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { ArrayList array = new ArrayList(); READAGAIN: while (port.BytesToRead > 0) { array.Add((byte)port.ReadByte()); } Thread.Sleep(timeStamp); if (port.BytesToRead > 0) { goto READAGAIN; } InitializedListView2(array); } delegate void SetInfo(ArrayList infos); public void InitializedListView2(ArrayList arrayList) { try { if (this.label2.InvokeRequired) { SetInfo ss = new SetInfo(InitializedListView2); this.Invoke(ss, new object[] { arrayList }); } else { byte[] data = new byte[arrayList.Count + 1]; string str = ""; for (int i = 0; i < arrayList.Count; i++) { data[i] = (byte)(arrayList[i]); string aa = data[i].ToString("X"); str += (data[i].ToString("X").Length == 2 ? data[i].ToString("X") : "0" + data[i].ToString("X")) + " "; } if (str.Trim().Equals("00 1E 98")) { label2.Text = "离开红外感应!"; } else if (str.Trim().Equals("00 1E 9E")) { label2.Text = "进入红外感应!"; MessageBox.Show("警告", "确认", MessageBoxButtons.OKCancel,MessageBoxIcon.Warning); int sleepTime = Convert.ToInt32(ConfigurationSettings.AppSettings["sleepTime"]); Thread.Sleep(sleepTime); } else { label2.Text = "错误!"; } textBox1.Text += str + "\r\n"; } } catch (Exception e) { MessageBox.Show(e.Message); } } protected void DataReceived(string info) { // rtbSerialInfo.Text += (SignalToHexCode(info).ToUpper()) + "\r\n"; switch (info) { case "00 1E 98": label2.Text = "离开红外感应!"; break; case "00 1E 9E": label2.Text = "进入红外感应!"; break; default: label2.Text = "错误!"; break; } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Show(); this.WindowState = FormWindowState.Normal; this.Activate(); } } private void Form1_Load(object sender, EventArgs e) { string connstring = @"Data Source=NICHOLAS_D-PC;Initial Catalog=Text;uid=sa;pwd=sa"; SqlConnection conn = new SqlConnection(connstring); conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; //设置cmd的类型为存储过程 cmd.CommandText = "EXEC usp_CallSceneStep"; cmd.Connection = conn; SqlParameter pCustomerID = new SqlParameter(); pCustomerID.ParameterName = "@CustomerID"; pCustomerID.SqlDbType = SqlDbType.NChar; pCustomerID.Value = "ALFKI"; cmd.Parameters.Add(pCustomerID); if (this.WindowState == FormWindowState.Minimized) { this.Visible = false; } } private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); } //鼠标双击图标,显示界面 private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) { this.Visible = true; this.TopMost = true; this.WindowState = FormWindowState.Normal; this.Activate(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) //关闭按钮事件 { e.Cancel = true; this.Hide(); } //最小化到托盘 private void Form1_SizeChanged(object sender, EventArgs e) //最小化事件按钮 { this.Hide(); } //托盘右键显示 private void hideMenuItem_Click(object sender, EventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; this.Activate(); } //托盘右键隐藏 private void showMenuItem_Click(object sender, EventArgs e) { this.Hide(); } //托盘右键退出 private void exitMenuItem_Click_1(object sender, EventArgs e) { if (MessageBox.Show("你确定要退出终端服务程序吗?", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) { notifyIcon1.Visible = false; this.Close(); this.Dispose(); Application.Exit(); } } } }
现在这个代码是串口为手选的。改为Xml形式更改串口号
毛毛,还没解决啊?
还有一个呢。我这个串口是直接读取的,现在需求就是改成Xml来配置。。。很纠结啊,解决完这个基本就完事了。
@董毛毛:
/// <summary> /// 获取端口 /// </summary> /// <param name="HardType"></param> /// <returns></returns> public static string GetPort(string HardType) { string port = ""; if (System.IO.File.Exists("HardwareParam.xml")) { XElement xel = XElement.Load("HardwareParam.xml"); if (xel.Element(HardType).Element("Port") != null) { port = xel.Element(HardType).Element("Port").Value; } }
你的业务我们肯定是不清楚的,但是看你的意思是想从xml文件中读配置好的数据,那简单的说就是操作xml文件档,这个比你上面的代码要简单多了,Google下看个例子你应该就能整出来了
WinForm 的Setting就可以直接用