//加载 private void Form1_Load(object sender, EventArgs e) { INIFILE.Profile.LoadProfile();//加载所有 // 预置波特率 switch (Profile.G_BAUDRATE) { case "300": cbBaudRate.SelectedIndex = 0; break; case "600": cbBaudRate.SelectedIndex = 1; break; case "1200": cbBaudRate.SelectedIndex = 2; break; case "2400": cbBaudRate.SelectedIndex = 3; break; case "4800": cbBaudRate.SelectedIndex = 4; break; case "9600": cbBaudRate.SelectedIndex = 5; break; case "19200": cbBaudRate.SelectedIndex = 6; break; case "38400": cbBaudRate.SelectedIndex = 7; break; case "115200": cbBaudRate.SelectedIndex = 8; break; default: { MessageBox.Show("波特率预置参数错误。"); return; } } //预置数据位 switch (Profile.G_DATABITS) { case "5": cbDataBits.SelectedIndex = 0; break; case "6": cbDataBits.SelectedIndex = 1; break; case "7": cbDataBits.SelectedIndex = 2; break; case "8": cbDataBits.SelectedIndex = 3; break; default: { MessageBox.Show("数据位预置参数错误。"); return; } } //预置停止位 switch (Profile.G_STOP) { case "1": cbStop.SelectedIndex = 0; break; case "1.5": cbStop.SelectedIndex = 1; break; case "2": cbStop.SelectedIndex = 2; break; default: { MessageBox.Show("停止位预置参数错误。"); return; } } //预置校验位 switch (Profile.G_PARITY) { case "None": cbParity.SelectedIndex = 0; break; case "Odd": cbParity.SelectedIndex = 1; break; case "Even": cbParity.SelectedIndex = 2; break; default: { MessageBox.Show("校验位预置参数错误。"); return; } } //预置CAN速率 switch (Profile.G_RATE) { case "10": canRate.SelectedIndex = 0; break; case "20": canRate.SelectedIndex = 1; break; case "50": canRate.SelectedIndex = 2; break; case "100": canRate.SelectedIndex = 3; break; case "125": canRate.SelectedIndex = 4; break; case "250": canRate.SelectedIndex = 5; break; case "500": canRate.SelectedIndex = 6; break; case "800": canRate.SelectedIndex = 7; break; case "1024": canRate.SelectedIndex = 8; break; default: { MessageBox.Show("CAN速率预置参数错误。"); return; } } //检查是否含有串口 string[] str = SerialPort.GetPortNames(); if (str == null) { MessageBox.Show("本机没有串口!", "Error"); return; } //添加串口项目 foreach (string s in System.IO.Ports.SerialPort.GetPortNames()) {//获取有多少个COM口 //System.Diagnostics.Debug.Write(s); cbSerial.Items.Add(s); } //message string sql_m = "select * from cantoolapp.canmessage"; SqlHelper.connect(); SqlDataReader sqldr_m = SqlHelper.query(sql_m); while (sqldr_m.Read()) { string messageName = (string)sqldr_m["messagename"]; CANMessageObject temp = new CANMessageObject(); temp.MessageName = messageName.ToCharArray(); temp.Id = Convert.ToUInt32(sqldr_m["id"]); canMessage.Add(temp); message.Items.Add(messageName); } SqlHelper.close(); //串口设置默认选择项 //cbSerial.SelectedIndex = 1; //note:获得COM9口,但别忘修改 Control.CheckForIllegalCrossThreadCalls = false; //这个类中我们不检查跨线程的调用是否合法(因为.net 2.0以后加强了安全机制,,不允许在winform中直接跨线程访问控件的属性) sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived); //sp1.ReceivedBytesThreshold = 1; //准备就绪 sp1.DtrEnable = true; sp1.RtsEnable = true; //设置数据读取超时为1秒 sp1.ReadTimeout = 1000; sp1.Close(); }