现在要做每个示波器通道按钮的点击时间,每个按钮我采用的是pictureBox,点击后会关闭或打开当前通道,同时对应图片变化;
其实每个按钮里面的逻辑都是一样的,可以批量处理。需要解决的问题有
1.怎么知道当前点击的是哪个pictureBox,然后加载正确的图片;
原来是每个图片各自加载,代码如下:
这里踩了一个坑,图片命名原来是CH1-OFF,结果导进Resource,名字自动变成了下划线;单独设置图片时名字用“_”
pictureBoxCh1.Image = Properties.Resources.CH1_OFF;
//通用写法
PictureBox pic=sender as PictureBox;
pic.Image = Properties.Resources.CH1_OFF;
2.需要使用动态文件名来加载对应的通道图片;
char ch='1';
pic.Image = (Image)Properties.Resources.ResourceManager.GetObject("CH" + ch + "-OFF");
这里文件名就要用真实文件命中的“-”,“CH1-OFF”而不能是“CH1_OFF”,以后可不能这样命名了,一改名字一会就搞崩了
3.怎么把四个通道代码写在一起
我先把四个通道放在一个Name为”panelCh“的Panel里面,四个PictureBox分别命名为"pictureBoxCh1"-”pictureBoxCh4",这样就可以根据控件的Name属性判断点的到底是哪个通道了。
然后在Form_Load里面加上一句
this.panelCh.Controls.OfType<PictureBox>().ToList().ForEach(PictureBox => PictureBox.Click += OnChPictureClickHandler);
再写个方法接收点击事件
private void OnChPictureClickHandler(object sender, EventArgs e)
{
if (initializeFlag != 1)
{
MessageBox.Show("请先初始化示波器连接。", "提示");
return;
}
PictureBox pic = sender as PictureBox;
string cname =pic.Name.ToString();
string ch = cname.Substring(cname.Length - 1);
oscilloscope.Write(cmd.ChOnOff(ch, "?"));
string str = oscilloscope.ReadString().Trim();
if (str == "1")
{
oscilloscope.Write(cmd.ChOnOff(ch, " 0"));
pic.Image = (Image)Properties.Resources.ResourceManager.GetObject("CH" + ch + "-OFF");
//pic.Image = Properties.Resources.CH2_OFF;
}
else
{
oscilloscope.Write(cmd.ChOnOff(ch, " 1"));
pic.Image = (Image)Properties.Resources.ResourceManager.GetObject("CH" + ch + "-ON");
}
}
//封装一下指令,用ch变量来控制对应通道
public string ChOnOff(string ch,string OnOff)//OnOff有" 1"," 0","?"三种状态,开启关闭带空格
{
return ":CHANnel" + ch + ":DISPlay" + OnOff;
}
4.连接示波器初始化过程中,每个通道状态获取,然后更新按钮pictureBoxCh1-pictureBoxCh4图片显示,要根据名字获取到对应控件,然后批量操作;
string str;
PictureBox pic;
String picname;
for (int i = 1;i<5;i++)
{
pic = (PictureBox)cmd.GetControlByName(panelCh,"pictureBoxCh" + i.ToString());
oscilloscope.Write(cmd.ChOnOff(i.ToString(),"?"));
str = oscilloscope.ReadString().Trim();
picname = str == "1" ? "-ON" : "-OFF";
pic.Image = (Image)Properties.Resources.ResourceManager.GetObject("CH" + i.ToString() + picname);
}
public Control GetControlByName(Control ctrl, string sCtrlName)
{
//根据控件名称找到控件
if (ctrl.Name == sCtrlName)
return ctrl;
else
foreach (Control subCtrl in ctrl.Controls)
{
Control sub = GetControlByName(subCtrl, sCtrlName);//应该叫递归
if (sub != null)
return sub;
}
return null;
}