我在Visual Studio 2013(C#)上构建一个Windows窗体程序,它从串行端口(在我的例子中是Arduino)读取数据并用它来更改图片。 Arduino返回一个8位字符串0和1,表示要更改的图片。例如 - 如果字符串为10001001
,则程序应更改第1版,第5版和第8张图片。该程序能够从串行端口(通过串行通信)获取正确的字符串,但是当我添加一个使图片发生变化的方法时,有时会给我这个错误:
未处理的类型' System.Reflection.TargetInvocationException'发生在mscorlib.dll
并指出Program.cs
上的那一行:
Application.Run(new Form1());
(我的表单名称为" form1.cs"名称空间为serial_read)
这是程序的样子:
这是我的form1.cs代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace Serial_receive
{
public partial class Form1 : Form
{
SerialPort serialPort1 = new SerialPort(); //Defines Serial Port
public Form1()
{
InitializeComponent();
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
foreach (string port in SerialPort.GetPortNames()) {comboBox1.Items.Add(port);} //Gives a list of the available ports
serialPort1.DataReceived += serialPort1_DataReceived;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string line = serialPort1.ReadLine(); //The serial string
this.BeginInvoke(new LineReceivedEvent(LineReceived), line);
}
private delegate void LineReceivedEvent(string line);
//Change image to a different image
private void changeColor(PictureBox ob, string line, int l) //ob = PictureBox, line = the serial string, l = number of PictureBox
{
if (int.Parse(line.Substring(l, 1)) == 1)
ob.Image = Serial_receive.Properties.Resources.red;
}
private void LineReceived(string line)
{
label1.Text = line;
changeColor(l1, line, 0); //Picture 1
changeColor(l2, line, 1); //Picture 2
changeColor(l3, line, 2); //Picture 3
changeColor(l4, line, 3); //Picture 4
changeColor(l5, line, 4); //Picture 5
changeColor(l6, line, 5); //Picture 6
changeColor(l7, line, 6); //Picture 7
changeColor(l8, line, 7); //Picture 8
}
private void button1_Click(object sender, EventArgs e) //Start Button
{
serialPort1.PortName = comboBox1.Text.ToString();
if (comboBox1.Text.ToString() == "Select Port... (Default: COM4)" || comboBox1.Text.ToString() == "")
serialPort1.PortName = "COM4";
serialPort1.Open();
button1.Enabled = false;
}
}
}
为什么我收到此错误的任何想法?我对C#有点新意,并不知道问题是什么......