图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});
}
}
}