编写一个使用模态对话框的项目,实现如图所示功能。要求:通过单击主窗体上的“调查”按钮弹出一个“市场调查”模态对话框,然后在模态对话框上选择相应的选项,把调查的结果反馈到主窗体上。
看这里 https://bbs.csdn.net/topics/360140208
主窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private MyDialog m_dlg;
private void toolStripButton1_Click(object sender, EventArgs e)
{
MyDialog dlg = new MyDialog(richTextBox1.Text);
if (dlg.ShowDialog() == DialogResult.OK)
{
richTextBox1.Text = dlg.TextBoxValue;
}
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
if (m_dlg == null)
{
m_dlg = new MyDialog(richTextBox1.Text);
m_dlg.TextBoxChanged += new EventHandler(
(sender1, e1) =>
{ richTextBox1.Text = m_dlg.TextBoxValue; }
);
m_dlg.FormClosed += new FormClosedEventHandler(
(sender2, e2) => { m_dlg = null; }
);
m_dlg.Show(this);
}
else
{
m_dlg.Activate();
}
}
}
}
子窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class MyDialog : Form
{
public event EventHandler TextBoxChanged;
public string TextBoxValue
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
public MyDialog() : this("") { }
public MyDialog(string Param)
{
InitializeComponent();
TextBoxValue = Param;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (TextBoxChanged != null)
TextBoxChanged(this, e);
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
}
}
窗体的公有属性值是最科学的方法。
对话框窗口定义一个属性,类似:public string ResultText { get; set; }
,类型根据要返回的内容的复杂度,可以用Dictionary或者JSON都可;
this.ResultText = this.radioButton3.Text;
this.DialogResult = DialogResult.OK;
类似这样使用:
var frm2 = new Form2();
var result = frm2.ShowDialog();
if (result == DialogResult.OK)
{
this.textBox1.AppendText($"{frm2.ResultText}{Environment.NewLine}");
}
修改元素属性
添加弹窗标题
运行显示效果