我无法从Form1修改属于Form 2的元素。
public partial class Project : Form
{
public Form2 form = new Form2();
public Project()
{
InitializeComponent();
}
private void Project_Load(object sender, EventArgs e)
{
form.CreateControl();
}
private void buttonOpenForm2_Click(object sender, EventArgs e)
{
form.Show();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
var indata = *whatever serial input data here*
bool result = Int32.TryParse(indata, out int data);
if (result) {
form.chart1.Invoke(new Action(() => { form.chart1.Series[0].Points.AddY(data); }));
}
}
每当我按下按钮以显示Form2及其图表时,form.chart1.Invoke
中就会引发异常:Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
如果我强迫form
进行CreateControl()
,为什么会发生这种情况?
答案 0 :(得分:1)
错误消息告诉您出什么问题了。
在form2
(保存图表)完全创建之前,您的串行端口正在触发
我想您可以检查可见标记(可能还有很多其他标记)
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
...
if(!form?.Visible)
return;
form.chart1.Invoke(...
假设是如果它不可见,则您不想显示数据
进一步阅读
Order of Events in Windows Forms
应用程序启动和关闭事件
Form和Control类公开了一组与 应用程序启动和关闭。 Windows Forms应用程序时 开始时,主表单的启动事件在 以下顺序:
Control.HandleCreated
Control.BindingContextChanged
Form.Load
Control.VisibleChanged
Form.Activated
显示的表单