我的 C# Windows 表单应用程序有问题,我正在尝试更改 tabControl1 中的活动选项卡,当我单击按钮 1 时它可以工作,但当我发送串行数据时,页面更改,但程序崩溃。
串行数据由Arduino发送,它每2秒仅发送"S"。
这是我用来测试的代码:
public partial class Form1 : Form
{
int page = 0;
public Form1()
{
InitializeComponent();
serialPort1.Open();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
page++;
if (page == 4)
{
page = 0;
}
tabControl1.SelectedIndex = page;
tabControl1.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
page++;
if (page == 4)
{
page = 0;
}
tabControl1.SelectedIndex = page;
tabControl1.Refresh();
}
}
这是一个错误,还是我以错误的方式做?
当数据 从串行端口对象接收。
https://msdn.microsoft.com/fi-fi/library/system.io.ports.serialport.datareceived(v=vs.110(.aspx
您必须使用 Invoke 方法来修改窗体主线程 UI 元素。
//Create a delegate
public delegate void ModifyTabPage();
//Create an object in the form for delegate and instatiate with the method which modifies tabpage
public ModifyTabPage myDelegate;
myDelegate = new ModifyTabPage(ModifyTabPageMethod);
public void ModifyTabPageMethod()
{
page++;
if (page == 4)
{
page = 0;
}
tabControl1.SelectedIndex = page;
tabControl1.Refresh();
}
//using invoke access it from the data recived event of your serialize port.
myFormControl1.Invoke(myFormControl1.myDelegate);
这应该有效。