这次用C#写个简单的窗口程序,这篇文章完全是面向新手的。
我简单说明一下我们要实现的功能:
有两个窗体Form1和Form2,这两个窗体里面都有一个TextBox和一个Button。
①当单击Form1里面的Button时,加载出Form2,同时Form2里的TextBox内容和Form1里的TextBox的内容一致;
②当单击Form2里面的Button时,销毁Form2,同时Form1里的TextBox内容变成Form2里TextBox的内容。
我们启动VS,并绘制两个如下图所示的窗体
绘制完成后,我们来到Form1.cs中,右击TextBox选择属性
在弹出的窗口中将其Modifiers属性设置为public
完成后也要将Form2的TextBox也进行同样的设置。只有这样两个窗体中的TextBox才可以相互“看得见”。
设置完成后,我们便可以进行我们的代码设计了!
首先我们来到Form1.cs中,双击Button1,进入代码设计窗口,我们可以看到VS已经帮我们把框架搭好了,直接上手就好喽!
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace WindowsFormsApplicationTest{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form_two = new Form2(); //实例化Form2 form_two.Show(); //将实例化的对象显示出来 form_two.textBox1.Text = this.textBox1.Text; //将Form1里TextBox的内容赋值给Form2里TextBox } }}
这样我们运行一下,发现功能①已经可以实现了!
下面继续实现②中的功能吧,我们选中Form2.cs,双击Button1,进入代码设计页面
首次我们要先声明一个Form1的对象
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace WindowsFormsApplicationTest{ public partial class Form2 : Form { public Form2() { InitializeComponent(); } public Form1 form_one; //声明Form类变量 private void button1_Click(object sender, EventArgs e) { } }}
然后我们要回到Form1的代码设计窗口,为form_one赋值。
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace WindowsFormsApplicationTest{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form_two = new Form2(); //实例化Form2 form_two.Show(); //将实例化的对象显示出来 form_two.textBox1.Text = this.textBox1.Text; //将Form1里TextBox的内容赋值给Form2里TextBox form_two.form_one = this; //将form_one指向Form1窗口 } }}
然后我们再次回到Form2的代码设计界面,实现赋值和销毁功能
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace WindowsFormsApplicationTest{ public partial class Form2 : Form { public Form2() { InitializeComponent(); } public Form1 form_one; //声明Form类变量 private void button1_Click(object sender, EventArgs e) { form_one.textBox1.Text = this.textBox1.Text; //将Form2里TextBox的内容赋值给Form1里TextBox this.Close(); //将Form2销毁 } }}运行一下,会发现我们的功能已经全部实现了!