图2 不带EventArgs的委托演示
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace hackpig
{
public class myFormControl : Form
{
public delegate void addListItem(String str1);
public addListItem myDelegate;
p rivate Button myButton;
p rivate ListBox myListBox;
p rivate Thread myThread;
public myFormControl()
{
myButton = new Button();
myListBox = new ListBox();
myButton.Location = new Point(72, 160);
myButton.Size = new Size(152, 32);
myButton.Text = "增加项目到listbox";
myButton.TabIndex = 1;
myButton.Click+=new EventHandler(myButton_Click);
//myButton.Invoke();
myListBox.Location = new Point(48, 32);
myListBox.Size = new Size(200, 95);
myListBox.Name = "list1";
myListBox.TabIndex = 2;
ClientSize = new Size(292, 273);
Controls.AddRange(new Control[] { myButton, myListBox });
Text = "控件的Invoke的演示程序";
myDelegate = new addListItem(addListItemMethod);
}
public void addListItemMethod(String str1)
{
myListBox.Items.Add(str1);
}
p rivate void myButton_Click(object sender, EventArgs e)
{
myThread = new Thread(new ThreadStart(threadFunction));
myThread.Start();
}
p rivate void threadFunction()
{
myThreadClass myThreadClassObject = new myThreadClass(this);
myThreadClassObject.run();
}
static void Main()
{
myFormControl myForm = new myFormControl();
myForm.ShowDialog();
}
}
//=================================
public class myThreadClass
{
myFormControl myFormControl_1;
public myThreadClass(myFormControl myform)
{
myFormControl_1 = myform;
}
public void run()
{
String str1 = "猪悟能";
myFormControl_1.Invoke(myFormControl_1.myDelegate,new object[]{str1});
}
}
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步