背景
这两天在重新复习事件,比如Winform控件的事件,利用vs很方便地实现。比如:想要在窗体加载时,修改窗口的标题;我们只需要双击Form1的标题栏即可;
vs便会给我们生成如下代码,且光标自动定位到方法体中:
private void Form1_Load( object sender, EventArgs e ) {}
然后我们在方法体中写上修改窗口标题的代码:
private void Form1_Load( object sender, EventArgs e ) {this.Text = "通过代码添加的控件的事件";}
运行即可看到效果:
然后我在想,如果是我通过代码添加的控件,比如一个button1,一个texbox1控件,那么在设计时虚拟窗体并不能看到他们,我怎么给他添加事件呢?
为了形成对比我们,在Form1窗体上除了代码添加的一个button1,一个texbox1控件,再手动拖拽一个button2控件;
给窗体添加3个控件
(1)button2直接在虚拟窗体直接上从工具箱拖上去;
(2)重点说明下代码自动生成的button1和textbox1;代码如下:
先定义一个私有方法:
private void CreatFormLayout(Form form,out TextBox tBox,out Button bton ) {TextBox textBox = new TextBox( );Button button = new Button( );textBox.Location = new Point( 1,1);textBox.Multiline = true;textBox.Size = new Size( 500,200);textBox.Font = new Font("正楷",24f);button.Location = new Point( 1,210);button.Size = new Size( 300,80);button.Text = "我是代码自动生成的按钮,请按我!";tBox = textBox;//textBox输出到对象tBoxbton = button;//button输出对象到btonform.Controls.Add( textBox);form.Controls.Add( button);}
在Main主程序中调用:
public partial class Form1 : Form{private TextBox textBox1;//定义控件字段接受代码输出的控件private Button button1;public Form1( ) {InitializeComponent( );CreatFormLayout(this, out textBox1, out button1);
(3)给button1添加事件:
this.button1.Click += Button1_Click;//事件的第四步——挂接事件
Note:小窍门——
------>
------>
我们在button1的事件处理器(响应事件的方法)中写入代码:
this.textBox1.Font = new Font("华文新魏", 22.2f, FontStyle.Bold);this.textBox1.Text = "我响应了button1按下的事件。";
点击button1,就是代码自动生成的那个按钮:
点击查看完整示例代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WindowsFormsApp3
{public partial class Form1 : Form{private TextBox textBox1;//定义控件字段接受代码输出的控件private Button button1;public Form1( ) {InitializeComponent( );CreatFormLayout(this, out textBox1, out button1);this.button1.Click += Button1_Click1;//事件的第四步——挂接事件this.textBox1.Text = "我是代码生成的textbox";}private void Button1_Click1( object sender, EventArgs e ) {this.textBox1.Font = new Font("华文新魏", 22.2f, FontStyle.Bold);this.textBox1.Text = "我响应了button1按下的事件。";}private void CreatFormLayout(Form form,out TextBox tBox,out Button bton ) {TextBox textBox = new TextBox( );Button button = new Button( );textBox.Location = new Point( 1,1);textBox.Multiline = true;textBox.Size = new Size( 500,200);textBox.Font = new Font("正楷",24f);button.Location = new Point( 1,210);button.Size = new Size( 300,80);button.Text = "我是代码自动生成的按钮,请按我!";tBox = textBox;//textBox输出到对象tBoxbton = button;//button输出对象到btonform.Controls.Add( textBox);form.Controls.Add( button);}private void button2_Click( object sender, EventArgs e ) {this.textBox1.Text = "我是button2按下。";}private void Form1_Load( object sender, EventArgs e ) {this.Text = "通过代码添加的控件的事件";button2.Size = new Size(300, 80);button2.Location = new Point(1, 300);}}
}