Invoke(Delegate)的用法:
//例如,要实时update窗体。如果在另一个线程中update,那么可以直接update(可以不在新线程中);也可以在Delegate中给出upate,然后invoke调用(但是invoke必须在另一线程中) //区别在于invoke是同步的(在此处,同步是啥意思) //参数Delegate拥有某个窗体句柄的控制权,即Delegate是在窗体类中定义的 —— 故update操作应在Delegate中 //invoke应该在另一个线程中调用;返回值为Delegate的返回值 class MyFormControl : Form { public delegate void AddListItem(); public AddListItem myDelegate; private Thread myThread; public MyFormControl() { myDelegate = new AddListItem(AddListItemMethod); myThread = new Thread(new ThreadStart(ThreadFunction)); myThread.Start(); } public void AddListItemMethod() { //update } private void ThreadFunction() { MyThreadClass myThreadClassObject = new MyThreadClass(this); myThreadClassObject.Run(); } } class MyThreadClass { MyFormControl myFormControl1; public MyThreadClass(MyFormControl myForm) { myFormControl1 = myForm; } public void Run() { myFormControl1.Invoke(myFormControl1.myDelegate); //myFormControl1.myDelegate(); } }
主要采用纯手写代码,生成窗体界面的方式(偶尔也可能拖控件)。
空工程创建一个窗体(但是现在是先弹出控制台——想办法去掉):
using System.Drawing; using System.Windows.Forms; namespace Project1 { class MyFormControl : Form { public MyFormControl() { ClientSize = new Size(292, 273); Text = "Custom Widget"; } static void Main() { MyFormControl myForm = new MyFormControl(); myForm.ShowDialog(); } } }
Button的创建及响应事件(下面的就不AddRange了):
//基于刚才的工程,在构造函数中新建一个button //Location、Size、TabIndex、Text、EventHandler myButton = new Button(); myButton.Location = new Point(72, 160); myButton.Size = new Size(152, 32); myButton.TabIndex = 1; myButton.Text = "Add items in list box"; myButton.Click += new EventHandler(Button_Click); Controls.AddRange(new Control[] { myButton });
ListBox的创建及用法:
myListBox = new ListBox(); myListBox.Location = new Point(48, 32); myListBox.Name = "myListBox"; myListBox.Size = new Size(200, 95); myListBox.TabIndex = 2; //添加项 string myItem = "1"; myListBox.Items.Add(myItem); myListBox.Update();