学习想法:一个简单的Form1-Form2间的数值传输程序,Form1是主窗口,Form2是弹窗,把Form2 中TextBox1当前输入信息通过Button1确认按钮进行判断确认后传递到Form1TextBox1信息录入窗口中,也可以通过Button2 退出按钮恢复Form2 中的TextBox2上次输入信息到Form1 TextBox1信息录入窗口中。
第一步:在工具箱中拖动对应控件到窗口Form1中,Button : Button1 , TextBox : TextBox 。
第二步:修改相关Form2控件相关设置,开始位置设定居中
第三步:建立窗口Form2,在工具箱中拖动对应控件到窗口Form2中,Button : Button1确认按钮、TextBox : TextBox 退出按钮,TextBox : TextBox1 当前输入、TextBox2 上次输入。
第四步:修改相关Form2控件相关设置,窗口尺寸设定600,100,开始位置设定居中
第五步:建立Form1 录入按钮 Button1_Click 事件,并输入以下代码
//录入按钮事件
private void button1_Click(object sender, EventArgs e)
{
string txtValue = this.textBox1.Text;
Form2 f2 = new Form2(txtValue);
f2.ShowDialog();
this.textBox1.Text = f2.returnValue;
}
第六步:建立Form1信息录入文本框事件属性中 textBox1_KeyPress 事件 ,并输入以下代码
//设定信息录入文本框禁止键盘输入
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true; //使用户的输入失效
}
第七步:修改Form2 初始化事件 ,并输入以下代码
//初始化
public Form2(string txtValue)
{
InitializeComponent();
this.textBox2.Text = txtValue;
}
第八步:双击Form2 窗口建立 Form2_Load事件
//窗口打开事件
private void Form2_Load(object sender, EventArgs e)
{
this.textBox1.Select();//设置光标在TextBox1上
this.textBox1.Focus();
this.textBox1.Text = "";//设置TextBox1内容清空
}
第九步:建立Form2 确认按钮 Button1_Click 事件,并输入以下代码
//确认按钮事件
private void button1_Click(object sender, EventArgs e)
{
if(this.textBox1.Text != "")//判断当前输入内容
{
returnValue = this.textBox1.Text;
}
else
{
returnValue = this.textBox2.Text;
}
this.Close();
}
第十步:建立Form2 退出按钮 Button2_Click 事件,并输入以下代码
//退出按钮事件
private void button2_Click(object sender, EventArgs e)
{
returnValue = this.textBox2.Text;
this.Close();
}
第十一步:建立Form2信息录入文本框事件属性中 textBox2_KeyPress 事件 ,并输入以下代码
//设定上次输入文本框禁止键盘输入
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true; //使用户的输入失效
}
效果展示:
以上就是这次【WinForm] C# 学习录入信息弹窗过程,有看到文章的友友也可以私信共同学习哦!