绑定事件(click,load)示例:
为form1绑定click事件,并将主窗体的对象放到静态类中
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 实现弹出窗体2 Form2 form2 = new Form2(); form2.Show(); } private void Form1_Load(object sender, EventArgs e) { // 窗口加载完毕后,将当前窗体对象放入静态类中的静态字段中(资源共享) Class1._frm1Test = this; } }
为form2绑定click事件
public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form3 form3 = new Form3(); form3.Show(); } }
为form2绑定click事件(关闭所有窗体)
public partial class Form3 : Form { public Form3() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 实现关闭当前窗体 //this.Close(); // 实现关闭所有窗体(关闭主窗体就会关闭所有的窗体) Class1._frm1Test.Close(); } }
静态类(静态类中资源共享)
public static class Class1 { public static Form1 _frm1Test; }
绑定事件示例:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } /** * 为按钮1绑定点击事件 */ private void button1_Click(object sender, EventArgs e) { // 弹出弹窗 MessageBox.Show("我也爱你,么么哒!"); // 当点击弹窗的确定时,关闭主窗口 this.Close(); } /** * 为按钮2绑定鼠标划过事件 */ private void button2_MouseEnter(object sender, EventArgs e) { // 给按钮一个新坐标 // 1.获取按钮能够活动的最大宽度,窗体宽度 - 按钮宽度 int maxWidth = this.ClientSize.Width - button2.Width; // 2.获取按钮能够活动的最大高度,窗体高度 - 按钮高度 int maxHeight = this.ClientSize.Height - button2.Height; // 3.生成随机坐标 Random r = new Random(); int x = r.Next(0, maxWidth + 1); // 由于不包括右边的值,所以要+1 int y = r.Next(0, maxHeight + 1); // 4.给按钮一个随机的坐标 button2.Location = new Point(x,y); } private void button2_Click(object sender, EventArgs e) { // 弹出弹窗 MessageBox.Show("再见!!!"); // 当点击弹窗的确定时,关闭主窗口 this.Close(); } }