![](/img/trans.png)
[英]C# compile error: “Invoke or BeginInvoke cannot be called on a control until the window handle has been created.”
[英]$exception {Invoke or BeginInvoke cannot be called on a control until the window handle has been created.} System.InvalidOperationException
我创建了一个方法来编辑 WindowsForm 控件属性,如文本框的文本。 但是我在不同的类(不是 Form1 类)中创建了这个方法,这个方法将由按钮点击处理程序调用,如下所示:但我得到 [异常 {Invoke 或 BeginInvoke 不能在控件上调用直到]
private void button1_Click(object sender, EventArgs e)
{
Update_UI Update_UI = new Update_UI();
if (_client!=null )
{
_trigger = false;
_StatusTxtBox.InvokeEx(stb => stb.Text += CRLF + " Server Disconnecting....");
_client.Close();
_listener.Stop();
}
else
{
Update_UI.UpdateUI("Update 02");
//UpdateUI("Update_01");
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace Server_app
{
public class Update_UI
{
// To populate String:
public void UpdateUI(string s)
{
Form1 f = new Form1();
Func<int> fn = delegate ()
{
f._StatusTxtBox.AppendText(System.Environment.NewLine + s);
return 0;
};
f._StatusTxtBox.Invoke(fn);
}
}
}
谢谢,艾尔赛德
我在代码中这样做是为了将 Form1 作为 ref 参数传递给外部类,但是如何将另一个 windowsform 作为 ref 传递给此类
private void button1_Click(object sender, EventArgs e)
{
Form1 f = this as Form1;
Update_UI_Frm1 Update_UI = new Update_UI_Frm1();
if (_client!=null )
{
_trigger = false;
_StatusTxtBox.InvokeEx(stb => stb.Text += CRLF + " Server is Disconnecting....");
_client.Close();
_listener.Stop();
}
else
{
Update_UI.UpdateUIFrm1(ref f,"Update 02");
}
}
public class Update_UI_Frm1
{
// To populate String:
public void UpdateUIFrm1(ref Form1 refform,string s)
{
Form1 Frm1 = refform;
Func<int> fn = delegate ()
{
Frm1._StatusTxtBox.AppendText(System.Environment.NewLine + s);
return 0;
};
Frm1._StatusTxtBox.Invoke(fn);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.