窗体(windows项目)
一个窗体类包括主代码类和部分类(partial关键字修饰)。部分类:窗体名.Designer.cs
部分类的使用,是通过partial关键字修饰,可以把两个同名的类关联,本质上都是一个类,方便维护,编译器编译时,会把这两个类编译在一起。
主启动窗体:在Program中的Application.Run(new FrmMain());中启动,可以在Main方法中添加判断,判断程序是否重复执行,或者注册验证等。
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//注册校验
//是否重复启动
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
}
控件
控件和组件的区别,在于控件在窗体中是可见的、组件是不可见的,不占用窗体空间的大小。
控件的使用和创建:
1.创建控件的成员变量
2.初始化控件对象的成员变量属性
3.添加控件到当前容器Controls集合中,容器(窗体、panel、GroupBox)
例:在一个GroupBox容器中,添加一个Button按钮控件,这个按钮就会被添加到GroupBox.Controls中,GroupBox这个容器被添加到窗体的Controls。也就是控件先被添加的当前容器中的Controls,然后容器被添加到窗体的Constols。
//
// groupBoxTest
//
this.groupBoxTest.Controls.Add(this.btnLOGIN);
this.groupBoxTest.Location = new System.Drawing.Point(301, 28);
this.groupBoxTest.Name = "groupBoxTest";
this.groupBoxTest.Size = new System.Drawing.Size(223, 157);
this.groupBoxTest.TabIndex = 1;
this.groupBoxTest.TabStop = false;
this.groupBoxTest.Text = "测试";
//
// FrmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(672, 408);
this.Controls.Add(this.groupBoxTest);
this.Controls.Add(this.BtnTest);
this.Name = "FrmMain";
this.Text = "控件事件的关联";
this.groupBoxTest.ResumeLayout(false);
this.ResumeLayout(false);
通过Controls.Add()添加控件对象。
事件
windows项目程序中的事件处理机制
1.定义事件
2.处理事件
3.关联事件
4.激发事件
生活中的事件处理机制
例:交通信号灯的事件:1.要有一个交通信号灯的预案(红灯停、绿灯行)--定义事件
2.交通信号灯的具体方案(红灯停、绿灯行、闯红灯扣分)--处理事件
3.交通预案好具体方案的关联--关联事件
4.激发交通信号灯--激发事件
程序中的事件。以按钮单击事件分析模型。
第一、事件定义(框架自带的)框架已经提前定义好了相关事件。
第二、事件处理(我们选择的)
private void BtnTest_Click(object sender, EventArgs e)
{
}
第三、事件关联: this.BtnTest.Click += new System.EventHandler(this.BtnTest_Click);
第四、事件激发:(用户单击按钮的行为)
public FrmMain()
{
InitializeComponent();
this.BtnTest.Click += new System.EventHandler(this.BtnTest_Click);
}
private void BtnTest_Click(object sender, EventArgs e)
{
MessageBox.Show("关联了事件");
}