c#学习笔记
-
语法相关
1.1 byte 数组
byte[] writeData = new byte[2];
byte[] readData = new byte[1];
1.2 string 数组
string[] charger_stat = new string[] {“Ready”,“Charge in progress”,“Charge done”,“Fault”,
};
1.3 string 二维 数组
public static String[,] g_select_string = {{“000–USB2.0 host with 100mA current limit”, “001-USB3.0 host with 150mA current limit”,“010–USB2.0 host with 500mA current limit”,“011–USB3.0 host with 900mA current limit”,“100–Charger with 1500mA current limit”,“101-Charger with 2000mA current limit”,“110-External ILIM current limit”,“111-No input current limit with internal clamp at 3A (PTM MODE)”},
{ “50 mA”,“75 mA”, “100 mA”, “125 mA”,“150 mA”,“175 mA”,“200 mA”,“225 mA”},
{ “Normal charge current set by 03h”, “Low charge current setting 330mA”, “NULL”,“NULL”,“NULL”,“NULL”,“NULL”,“NULL”},
{ “00–0.75 hour fast charge”, “01–6 hour fast charge”, “10–9 hour fast charge”,“11–Disable safety timers”,“NULL”,“NULL”,“NULL”,“NULL”},
};
1.4 string 数组list
ArrayList g_label1_str = new ArrayList(label1_str); // 初始化
int index = g_label1_str.IndexOf(label1.Text); // 通过字符串找下标
1.5 字符串处理
1.5.1 substring
截取子串,第一个参数从第几个字符开始,第二个参数,长度
for (int k = 0; k <= 7; k++)
{
dataGridView1[k + 2, i].Value = d.Substring(k, 1);
}
1.5.2 tostring
val = (k * 0.02 + 3.5).ToString(“F2”) + " V"; // 转化成2位小数的float
addr = val.ToString(); // 转化成字符串
1.5.3 string ascii 转化
//ASCII转字符串
public static string Ascii2Str(byte[] buf)
{
return System.Text.Encoding.ASCII.GetString(buf);
}
//字符串转ASCII
public static byte[] str2ASCII(String xmlStr)
{
return Encoding.Default.GetBytes(xmlStr);
}
1.6 Convert
字符串为0xA1 时,第二个参数不写成16 ,会出错。意思是16进制的字符串
row_index = Convert.ToByte(label2.Text.Substring(1, 2), 16) / 16;
Convert 成int 后在转换成16进制的字符串,X2 表示2位,大写。
Convert.ToInt32(Params[i + 1]).ToString(“X2”)
转化成二进制,第二个参数是2.
Convert.ToString(Convert.ToInt32(Params[i + 1]), 2).PadLeft(8, ‘0’); // PadLeft(8,‘0’),不足8 位,左补0
- 常用基础组件
2.1 combox
2.1.1 定义及样式
ComboBox[] Combo = new ComboBox[15];
样式如下:
2.1.2 添加下拉框的元素
for (k = 0; k < 8; k++)
{
val = (k * 0.08 + 4.2).ToString(“F2”) + " V";
Combo[i].Items.Add(val);
}
AutoRcomboBox.Items.Add(“Auto Read OFF”);
comboBox1.Items.AddRange(pmbus_datagrid_alphabet_command_str); // 添加字符串数组
2.1.3 其他用法
多个中断处理函数合成一个通用的
for (i = 0; i < 8; i++)
{
Combo[i].SelectionChangeCommitted += new EventHandler(ComboBox_SelectionChange); //Combo内容改变事件
Combo[i].MouseMove += new MouseEventHandler(comboBox_MouseMove); //鼠标进入Combo事件
Combo[i].MouseLeave += new EventHandler(comboBox_MouseLeave); //鼠标离开Combo事件
Combo[i].MouseClick += new MouseEventHandler(comboBox_MouseClick); //鼠标点击Combo事件
Combo[i].Height += 20;
}
ComboBox_SelectionChange函数的处理
private void ComboBox_SelectionChange(object sender, EventArgs e)
{
for (r = 0; r < 8; r++)
{
if (sender == Combo[r]) // 得到当前是哪一个combox
{
break;
}
}
}
直接赋值文本
comboBox1.Text = “哈哈哈哈”
SerialNumcomboBox.SelectedIndex = 1;//显示第一个元素
清除元素
comboBox1.Items.Clear();
获取显示的元素字符
Readindx = AutoRcomboBox.SelectedItem.ToString();
for (int i = 0; i < 8; i++) //多字节中Combo颜色复位
{ Combo[i].BackColor = SystemColors.Window; }
2.2 label
2.2.1 定义及样式
Label[] labelA = new Label[15];
2.2.2 其他用法
labelA[k].TextAlign = ContentAlignment.MiddleRight; //label 文本对齐方式
label3.Text = “x” + temp_value.ToString(“X2”) // label 的文本显示
2.3 CheckBox
2.3.1 定义及样式
CheckBox[] Check = new CheckBox[13];
2.3.2 基本用法
多个中断处理函数合成一个通用的
for (i = 0; i < 13; i++)
{
Check[i].MouseUp += new MouseEventHandler(checkBox_MouseUp);
Check[i].MouseMove += new MouseEventHandler(this.checkBox_MouseMove);
Check[i].MouseLeave += new EventHandler(checkBox_MouseLeave);
}
for (r = 0; r < 13; r++)
{ if (sender == Check[r]) break; } //当前是哪一个chechbox 的中断事件
判断checkbox 是否选中
if (Check[r].Checked == true)
val = 1;
2.4 TextBox
2.4.1 定义及样式
TextBox[] TextA = new TextBox[7];
2.4.2 基本用法
显示的文本
TextA[0].Text = “WD timeout”;
textBox16.Multiline = true; //多行显示:
textBox16.ScrollBars = ScrollBars.Vertical; // textbox 的滚动条
2.5 Button
2.5.1 定义及样式
2.5.2 基本用法
button17.Text = “123”; // 按钮显示的文本
button17.BackColor = Color.Yellow; //按钮的背景色
private void button2_Click(object sender, EventArgs e) // button 点击函数
2.6 numericUpDown1
2.6.1 定义及样式
this.numericUpDown3 = new System.Windows.Forms.NumericUpDown();
numericUpDown10.DecimalPlaces = 1; //减少的步进
numericUpDown10.Increment = (decimal)0.5; //增加的步进
numericUpDown10.Maximum = (decimal)15.5; //最大
numericUpDown10.TextAlign = HorizontalAlignment.Center; //对齐方式
2.6.2 基本用法
numericUpDown1.Value = temp_value; // 赋值
numericUpDown1.Enabled = true; // 使能
value值改变 事件处理
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
2.7 radioButton
2.7.1 定义及样式
this.radioButton2 = new System.Windows.Forms.RadioButton();
2.7.2 基本用法
radioButton21.Checked = true; //选中
radioButton9.TextAlign = ContentAlignment.TopLeft; // 对齐方式
2.8 trackBar
2.8.1 定义及样式
this.trackBar1 = new System.Windows.Forms.TrackBar();
2.8.2 基本用法
value值改变 事件处理
private void trackBar1_ValueChanged(object sender, EventArgs e)
{
label51.Text = "OTP: " + trackBar1.Value.ToString() + “℃”;
}
trackBar1.Value = (int)true_value; // 直接赋值
2.9 groupBox
2.9.1 定义及样式
this.groupBox1 = new System.Windows.Forms.GroupBox();
2.9.2 基本用法
groupBox1.Top = 2;
groupBox1.Left = Combo[0].Height / 4;
groupBox1.Height = Combo[4].Top + Combo[4].Height + Combo[4].Top/5;
groupBox1.Width = Combo[3].Left + Combo[3].Width + Combo[0].Top / 2;
2.10 panel
2.10.1 定义及样式
this.panel1 = new System.Windows.Forms.Panel();
Panel[] pmbus_panel = new Panel[69];
2.10.2 基本用法
panel6.Left = textBox15.Left; //panel 离父容器的left 距离
panel6.Width = 4 * tableLayoutpanel.Width / 10 - 20; //panel的 宽
panel6.Height = tableLayoutpanel.Height - panel6.Top - 10; //panel的高
panel6.BackColor = Color.LightGray; //背景色
panel6.Top = 2 //panel 离父容器的 top 距离
panel68.Visible = false; //隐藏panel
2.11 flowLayoutPanel
2.11.1 定义及样式
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
2.11.2 基本用法
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.BackColor = System.Drawing.SystemColors.HighlightText;
this.flowLayoutPanel1.Controls.Add(this.Driverbutton);
this.flowLayoutPanel1.Controls.Add(this.Backbutton);
this.flowLayoutPanel1.Controls.Add(this.OpenSerialbutton);
this.flowLayoutPanel1.Controls.Add(this.SerialNumcomboBox);
this.flowLayoutPanel1.Controls.Add(this.I2CSpeed);
this.flowLayoutPanel1.Controls.Add(this.I2CcomboBox);
this.flowLayoutPanel1.Controls.Add(this.SlvAddrlabel);
this.flowLayoutPanel1.Controls.Add(this.SlvAddrcomboBox);
this.flowLayoutPanel1.Controls.Add(this.AutoRcomboBox);
this.flowLayoutPanel1.Controls.Add(this.RAll);
this.flowLayoutPanel1.Controls.Add(this.WAll);
this.flowLayoutPanel1.Controls.Add(this.ACKlabel);
this.flowLayoutPanel1.Controls.Add(this.Testlabel);
this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top;
this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 8);
this.flowLayoutPanel1.Name = “flowLayoutPanel1”;
this.flowLayoutPanel1.Size = new System.Drawing.Size(1543, 39);
this.flowLayoutPanel1.TabIndex = 2;
2.12 tableLayoutpanel
2.12.1 定义及样式
//
// tableLayoutpanel
//
this.tableLayoutpanel.ColumnCount = 2;
this.tableLayoutpanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 40F));
this.tableLayoutpanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 60F));
this.tableLayoutpanel.Controls.Add(this.panel5, 0, 0);
this.tableLayoutpanel.Controls.Add(this.panel4, 1, 0);
this.tableLayoutpanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutpanel.Location = new System.Drawing.Point(3, 3);
this.tableLayoutpanel.Name = “tableLayoutpanel”;
this.tableLayoutpanel.RowCount = 1;
this.tableLayoutpanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutpanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 781F));
this.tableLayoutpanel.Size = new System.Drawing.Size(1213, 781);
this.tableLayoutpanel.TabIndex = 0;
2.13 toolStrip1
2.13.1 定义及样式
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
2.13.2 基本用法
//
// toolStrip1
//
this.toolStrip1.AutoSize = false;
this.toolStrip1.ImageScalingSize = new System.Drawing.Size(50, 50);
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButton1,
this.toolStripButton2,
this.toolStripButton3,
this.toolStripButton4,
this.toolStripButton5,
this.toolStripButton6,
this.toolStripButton7,
this.toolStripButton8,
this.toolStripButton9,
this.toolStripButton10,
this.toolStripButton11,
this.toolStripButton12,
this.toolStripButton13,
this.toolStripButton14,
this.toolStripButton15});
this.toolStrip1.Location = new System.Drawing.Point(0, 32);
this.toolStrip1.Name = “toolStrip1”;
this.toolStrip1.Size = new System.Drawing.Size(1532, 70);
this.toolStrip1.TabIndex = 1;
this.toolStrip1.Text = “toolStrip1”;
this.toolStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStrip1_ItemClicked);
里面子元素button 的点击处理
private void toolStripButton1_Click(object sender, EventArgs e)
{
}
2.14 menuStrip
2.14.1 定义及样式
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
2.14.2 基本用法
menuStrip 及其子元素
//
// menuStrip1
//
this.menuStrip1.GripMargin = new System.Windows.Forms.Padding(2, 2, 0, 2);
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(24, 24);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem1,
this.toolStripMenuItem2,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = “menuStrip1”;
this.menuStrip1.Size = new System.Drawing.Size(1532, 32);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = “menuStrip1”;
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.saveBoradDesignToolStripMenuItem});
this.toolStripMenuItem1.Name = “toolStripMenuItem1”;
this.toolStripMenuItem1.Size = new System.Drawing.Size(56, 28);
this.toolStripMenuItem1.Text = “File”;
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.ForeColor = System.Drawing.Color.Black;
this.openToolStripMenuItem.Name = “openToolStripMenuItem”;
this.openToolStripMenuItem.Size = new System.Drawing.Size(291, 34);
this.openToolStripMenuItem.Text = “Open Borad Design…”;
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
里面子元素button 的点击处理
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
}
2.15 treeView
2.15.1 定义及样式
this.treeView1 = new System.Windows.Forms.TreeView();
2.15.2 基本用法
this.treeView1.Location = new System.Drawing.Point(6, 0);
this.treeView1.Name = “treeView1”;
treeNode645.Name = “节点3”;
treeNode645.Text = “Loop 1::pmb x5D”;
treeNode646.Name = “节点4”;
treeNode646.Text = “Loop 2::pmb x5E”;
treeNode647.Name = “节点1”;
treeNode647.Text = “SGM63080::I2c X1D”;
treeNode648.Name = “节点2”;
treeNode648.Text = “SGM63080::I2c X30 to do…”;
treeNode649.Name = “节点0”;
treeNode649.Text = “Total Pout : 0.0W”;
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode649});
this.treeView1.Size = new System.Drawing.Size(244, 630);
this.treeView1.TabIndex = 3;
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
目录树的子节点 的text 表述
treeView1.TopNode.Nodes[0].Text = “SGM63080::I2c X” //目录树的TOP 节点的第一个子节点
treeView1.TopNode.Nodes[0].Nodes[0].Text = “Loop 1::pmb x” //目录树的TOP 节点的第一个子节点的第一个子节点
treeView1.TopNode.Nodes[0].Nodes[1].Text = “Loop 2::pmb x” //目录树的TOP 节点的第一个子节点的第二个子节点
目录树的点击之后事件处理
AfterSelect事件中写代码,第二次点同一个节点,事件不会触发。除非换单击别的节点才能继续触发afterselect事件。
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node.Level == 1)
{
if(e.Node == treeView1.TopNode.Nodes[0])
{
this.RegisterMap.Visible = true;
this.Pmbus.Visible = false;
}
}
else if (e.Node.Level == 2)
{
if (e.Node == treeView1.TopNode.Nodes[0].Nodes[0])
{
...
}
}
}
目录树的收缩与扩展
this.treeView2.ExpandAll(); //展开
this.treeView2.CollapseAll(); //收缩
目录树的节点单击事件
private void treeView2_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left) //单击鼠标左键才响应
{
if (e.Node.Level == 1) //判断子节点才响应
{
int index = g_map_arr.IndexOf(e.Node.Text);
}
}
2.16 dataGridView
2.16.1 定义及样式
this.dataGridView1 = new System.Windows.Forms.DataGridView();
2.16.2 基本用法
dataGridView1.Rows.Add(7);
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.CurrentCell = null;
dataGridView1.ClearSelection();
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.Columns[0].DefaultCellStyle.BackColor = SystemColors.Control;
dataGridView1.Columns[0].DefaultCellStyle.SelectionBackColor = SystemColors.Control;
dataGridView1.Columns[0].DefaultCellStyle.SelectionForeColor = Color.Black;
dataGridView1.Columns[1].DefaultCellStyle.SelectionBackColor = SystemColors.Window;
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White; // 颜色相关
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black; // 颜色相关
for (i = 2; i <= 9; i++)
{ dataGridView1.Columns[i].DefaultCellStyle.SelectionBackColor = Color.Yellow; }
dataGridView1.AdvancedColumnHeadersBorderStyle.Top = DataGridViewAdvancedCellBorderStyle.InsetDouble;
dataGridView1.MultiSelect = false;
dataGridView1.ColumnHeadersHeight = comboBox5.Height * 15 / 10;
4) 单元格的上下左右的边框线式样的单独设定
CellBorderStyle只能设定单元格全部边框线的式样。要单独改变单元格某一边边框式样的话,需要用到DataGridView.AdvancedCellBorderStyle属性。如示例:
’ 单元格的上边和左边线设为二重线
’ 单元格的下边和右边线设为单重线
DataGridView1.AdvancedCellBorderStyle.Top = _
DataGridViewAdvancedCellBorderStyle.InsetDouble
DataGridView1.AdvancedCellBorderStyle.Right = _
DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Bottom = _
DataGridViewAdvancedCellBorderStyle.Inset
DataGridView1.AdvancedCellBorderStyle.Left = _
DataGridViewAdvancedCellBorderStyle.InsetDouble
同样,设定行头单元格的属性是: AdvancedRowHeadersBorderStyle, 设定列头单元格属性是:AdvancedColumnHeadersBorderStyle。
for (i = 0; i < (this.dataGridView1.Columns.Count); i++)
{
this.dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;// 设置单元不可插入
this.dataGridView1.Columns[i].Width = dataGridView1.Width / 12; // 设置单元格宽度
if (i < (this.dataGridView1.Columns.Count - 2))
{
for (int j = 0; j < this.dataGridView1.Rows.Count; j++)
{
dataGridView1.Rows[j].Cells[i].Value = "0"; // 设置单元格value
dataGridView1.Rows[j].Height = comboBox5.Height; // 设置单元格高度
}
}
else
{
dataGridView1.Columns[10].HeaderText = "";
dataGridView1.Columns[11].HeaderText = "";
for (int j = 0; j < this.dataGridView1.Rows.Count; j++)
{
dataGridView1.Rows[j].Cells[10].Value = "R";
dataGridView1.Rows[j].Cells[11].Value = "W";
dataGridView1.Rows[j].Height = comboBox5.Height * 15 / 10;
}
for (int j = 0; j < this.dataGridView1.Rows.Count; j++)
{
string st = j.ToString("X2");
dataGridView1.Rows[j].Cells[0].Value = st;
}
}
}
dataGridView1.AllowUserToAddRows = false; // 不允许新增行
dataGridView1.AllowUserToDeleteRows = false; // 不允许删除行
dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //value 对齐方式
// 直接设置单元格的背景色
{ dataGridView1[i, reg].Style.BackColor = Color.Yellow; }
//点击事件
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
//-------------------------------------------Data列单击--------------------------------------------------------------------//
if (e.ColumnIndex == 1 && e.RowIndex >= 0) //判断行列的下标
{
dataGridView1.Columns[1].ReadOnly = false;
dataGridView1.CurrentCell = dataGridView1[e.ColumnIndex, e.RowIndex];
dataGridView1.BeginEdit(true); // 可以编辑
dataGrid_lastvalue = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
}
//-------------------------------------------内容单击------------------------------------------------------------------------//
if (e.ColumnIndex >= 2 && e.ColumnIndex <= 9 && e.RowIndex >= 0)
{
}
//-------------------------------------------R列单击------------------------------------------------------------------------//
if (e.ColumnIndex == 10 && e.RowIndex >= 0 && e.RowIndex < 7)
{
}
//-------------------------------------------W列单击------------------------------------------------------------------------//
if (e.ColumnIndex == 11 && e.RowIndex < 7 && e.RowIndex >= 0)
{
}
}
//编辑完成后事件
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
}
合并表头的标题
private void dataGridView4_Paint(object sender, PaintEventArgs e)
{
//Offsets to adjust the position of the merged Header.
int heightOffset = -5;
int widthOffset = 0;
int xOffset = 0;
int yOffset = 4;
//Index of Header column from where the merging will start.
int columnIndex = 0;
//Number of Header columns to be merged.
int columnCount = 3;
//Get the position of the Header Cell.
Rectangle headerCellRectangle = dataGridView4.GetCellDisplayRectangle(columnIndex, 0, true);
//X coordinate of the merged Header Column.
int xCord = headerCellRectangle.Location.X + xOffset;
//Y coordinate of the merged Header Column.
int yCord = headerCellRectangle.Location.Y - headerCellRectangle.Height + yOffset;
//Calculate Width of merged Header Column by adding the widths of all Columns to be merged.
int mergedHeaderWidth = dataGridView4.Columns[columnIndex].Width * columnCount + widthOffset;
//Generate the merged Header Column Rectangle.
Rectangle mergedHeaderRect = new Rectangle(xCord, yCord, mergedHeaderWidth, headerCellRectangle.Height + heightOffset);
//Draw the merged Header Column Rectangle.
e.Graphics.FillRectangle(new SolidBrush(Color.LightBlue), mergedHeaderRect);
//Draw the merged Header Column Text.
e.Graphics.DrawString("MFR/CNFG", dataGridView4.ColumnHeadersDefaultCellStyle.Font, Brushes.Black, xCord + 1, yCord + 1);
}
2.17 TabControl
2.17.1 定义及样式
this.RegisterMap = new System.Windows.Forms.TabControl();
2.17.2 基本用法
//
// RegisterMap
//
this.RegisterMap.AccessibleName = “Register Map”;
this.RegisterMap.Controls.Add(this.tabPage1);
this.RegisterMap.Controls.Add(this.tabPage2);
this.RegisterMap.Controls.Add(this.tabPage3);
this.RegisterMap.Location = new System.Drawing.Point(3, 0);
this.RegisterMap.Name = “RegisterMap”;
this.RegisterMap.SelectedIndex = 0;
this.RegisterMap.Size = new System.Drawing.Size(1227, 956);
this.RegisterMap.TabIndex = 0;
//
this.RegisterMap.Visible = false;
子页面的点击事件
private void tabPage2_Click(object sender, EventArgs e)
{
}
2.18 serialPort
2.18.1 定义及样式
2.17.2 基本用法
String serialPortName;
//串口端
string[] ports = System.IO.Ports.SerialPort.GetPortNames();//获取电脑上可用串口号
SerialNumcomboBox.Items.AddRange(ports);//给comboBox1添加数据
SerialNumcomboBox.SelectedIndex = SerialNumcomboBox.Items.Count > 0 ? 0 : -1;//如果里面有数据,显示第0个
串口对应的打开按钮
private void OpenSerialbutton_Click(object sender, EventArgs e)
{
if (OpenSerialbutton.Text == “Open Serial”)
{//如果按钮显示的是打开串口
try
{//防止意外错误
serialPort1.PortName = SerialNumcomboBox.Text;//获取comboBox1要打开的串口号
serialPortName = SerialNumcomboBox.Text;
serialPort1.BaudRate = 115200;//获取comboBox2选择的波特率
serialPort1.DataBits = 8;//设置数据位
/设置停止位/
serialPort1.StopBits = StopBits.One;
/*设置奇偶校验*/
serialPort1.Parity = Parity.None;
serialPort1.Open();//打开串口
OpenSerialbutton.Text = "Close Serial";//按钮显示关闭串口
delayUs(100);
toolStripStatusLabel1.Text = "Serial port has been opened";
toolStripStatusLabel1.ForeColor = Color.Green;
//Send_At_Cmd("AT+SADDR=110\r\n");
timer4.Enabled = true;
}
catch (Exception err)
{
timer4.Enabled = false;
timer3.Enabled = false;
MessageBox.Show("打开失败" + err.ToString(), "提示!");//对话框显示打开失败
}
}
else
{//要关闭串口
try
{//防止意外错误
serialPort1.Close();//关闭串口
timer4.Enabled = false;
timer3.Enabled = false;
}
catch (Exception) { }
OpenSerialbutton.Text = "Open Serial";//按钮显示打开
}
}
串口接手中断
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string str = “”;
System.Threading.Thread.Sleep(100);
do
{
int count = serialPort1.BytesToRead;
if (count <= 0)
break;
byte[] readBuffer = new byte[count];
//Application.DoEvents();
serialPort1.Read(readBuffer, 0, count);
str += System.Text.Encoding.Default.GetString(readBuffer);
} while (serialPort1.BytesToRead > 0);
//Testlabel.Text = str;
if (str.Contains("RREG:"))
{
Invoke((new Action(() => //C# 3.0以后代替委托的新方法
{
handle_read_buff(str, str.Length);
})));
}
else
{
Invoke((new Action(() => //C# 3.0以后代替委托的新方法
{
delayUs(50);
int ack = str.IndexOf("OK");
//delayUs(100);
if (-1 != ack)
{
ACKlabel.Text = "Device Write OK!";
ACKlabel.ForeColor = Color.Green;
}
else
{
ACKlabel.Text = "Device Write Fail!";
ACKlabel.ForeColor = Color.Red;
}
})));
}
}
判断串口是否打开
if (!serialPort1.IsOpen)
{
timer3.Enabled = false;
MessageBox.Show(“Serial port is not opened!”, “SGMICRO”, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
串口热插拔
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0219)
{//设备改变
if (m.WParam.ToInt32() == 0x8004)
{//usb串口拔出
toolStripStatusLabel1.Text = "Dongle offline !!!";
toolStripStatusLabel1.ForeColor = Color.Red;
string[] ports = System.IO.Ports.SerialPort.GetPortNames();//重新获取串口
SerialNumcomboBox.Items.Clear();//清除comboBox里面的数据
SerialNumcomboBox.Items.AddRange(ports);//给comboBox1添加数据
if (OpenSerialbutton.Text == "Close Serial")
{//用户打开过串口
if (!serialPort1.IsOpen)
{//用户打开的串口被关闭:说明热插拔是用户打开的串口
OpenSerialbutton.Text = "Open Serial";
serialPort1.Dispose();//释放掉原先的串口资源
SerialNumcomboBox.SelectedIndex = SerialNumcomboBox.Items.Count > 0 ? 0 : -1;//显示获取的第一个串口号
}
else
{
SerialNumcomboBox.Text = serialPortName;//显示用户打开的那个串口号
}
}
else
{//用户没有打开过串口
SerialNumcomboBox.SelectedIndex = SerialNumcomboBox.Items.Count > 0 ? 0 : -1;//显示获取的第一个串口号
}
}
else if (m.WParam.ToInt32() == 0x8000)
{//usb串口连接上
toolStripStatusLabel1.Text = "Dongle online !!!";
toolStripStatusLabel1.ForeColor = Color.Green;
string[] ports = System.IO.Ports.SerialPort.GetPortNames();//重新获取串口
SerialNumcomboBox.Items.Clear();
SerialNumcomboBox.Items.AddRange(ports);
if (OpenSerialbutton.Text == "Close Serial")
{//用户打开过一个串口
SerialNumcomboBox.Text = serialPortName;//显示用户打开的那个串口号
}
else
{
SerialNumcomboBox.SelectedIndex = SerialNumcomboBox.Items.Count > 0 ? 0 : -1;//显示获取的第一个串口号
}
}
}
base.WndProc(ref m);
}
3. 进阶用法
3.1 弹出新界面
// otp
// 点击弹框的图标按钮,弹出otp 的界面
private void toolStripButton11_Click(object sender, EventArgs e)
{
Form2 otp_form = new Form2();
otp_form.ShowDialog();
}
3.2 点击按钮安装驱动
private void Driverbutton_Click(object sender, EventArgs e)
{
string str = System.Environment.CurrentDirectory;
//str = str + “\驱动”;
str = str + “\SETUP”;
System.Diagnostics.Process.Start(str);
}
3.2 加载 配置文件
//load config
private void button6_Click(object sender, EventArgs e)
{
int row_index, column_index = 0;
//byte[] new_value;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Reset();
ofd.Title = “Load Register”;
ofd.FileName = “”;
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
ofd.Filter = “.txt|.txt”;
ofd.ValidateNames = true; //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
ofd.CheckFileExists = true; //验证路径有效性
ofd.CheckPathExists = true; //验证文件有效性
ofd.RestoreDirectory = true;
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
// 读入所有行
string[] lines = File.ReadAllLines(ofd.FileName);
// 点列表集合
// List<Point> points = new List<Point>();
// 让过第一行,从第二行开始处理
for (int i = 1; i < lines.Length - 1; i++)
{
string line = lines[i];
// 拆分行
string[] v = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (i == lines.Length - 2)
MessageBox.Show(v[1]);
row_index = (i + 0x23) / 16;
column_index = (i + 0x23) - 16 * row_index + 1;
byte old_value = Convert.ToByte((string)dataGridView1[column_index, row_index].Value, 16);
byte new_value = Convert.ToByte(v[1], 16);
if (old_value != new_value)
dataGridView1[column_index, row_index].Style.BackColor = Color.MediumSeaGreen;
dataGridView1[column_index, row_index].Value = v[1];
}
}
}
catch (Exception)
{
MessageBox.Show("Invalid Register Format!", "SGMICRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
3.2 保存 配置文件
//save config
private void button7_Click(object sender, EventArgs e)
{
string Save;
int row_index, column_index = 0;
// uint t;
//begin
Save = “17 00 00”;
for (int i = 0x24; i < 0xA6; i++)
{
row_index = i / 16;
column_index = i - 16 * row_index + 1;
// t = mStrToBcd(Convert.ToString(dataGridView1.Rows[i].Cells[1].Value));
Save += ("\r\n" + i.ToString("x2").ToUpper() + " " + dataGridView1[column_index, row_index].Value + " " + "FF");
}
//end
Save += "\r\nC2 F5 00";
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Save Register";
dlg.Filter = "*.txt|*.txt";//文件筛选器
dlg.AddExtension = true;//保存文件时自动加扩展名
dlg.FilterIndex = 1;//文件筛选器的索引,1为txt
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(dlg.FileName, false, Encoding.UTF8);
sw.Write(Save); // \r\n为换行
sw.Close();
}
}