Winform窗体text模态和非模态传值

PS:模态的意思:我们打开对话框,将值传进取,操作完成确定,主窗体再获得对话框的值;
非模态的意思:我们打开对话框,可以在不关闭窗口的情况下和主窗体交互,主窗体可以即时获得子窗体的值。

1.新建winform项目,添加两个winform窗体命名为:MainForm和Show;

2.MainForm中添加两个button,button1和button2,添加一个richTextBox,richtextBox命名为:richTextBoxMain;

Winform窗体text模态和非模态传值_第1张图片

3.Show窗体中添加一个textbox即可,命名为:textBoxShow;

Winform窗体text模态和非模态传值_第2张图片

4.MainForm中代码:

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 winform窗体两种传值
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private Show Show;

        private void button1_Click(object sender, EventArgs e)
        {
            Show my = new Show(richTextBoxMain.Text);
            if (my.ShowDialog() == DialogResult.OK)
            {
                richTextBoxMain.Text = my.TextBoxValue;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (Show == null)
            {
                Show = new Show(richTextBoxMain.Text);
                Show.TextBoxChanged += new EventHandler(
                    (sender1, e1) =>
                    { richTextBoxMain.Text = Show.TextBoxValue; }
                );
                Show.FormClosed += new FormClosedEventHandler(
                    (sender2, e2) => { Show = null; }
                );
                Show.Show(this);
            }
            else
            {
                Show.Activate();
            }
        }
    }
}

5.Show中代码:

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 winform窗体两种传值
{
    public partial class Show : Form
    {

        public event EventHandler TextBoxChanged;

        public string TextBoxValue
        {
            get { return textBoxShow.Text; }
            set { textBoxShow.Text = value; }
        }

        public Show() : this("") 
        { 
        
        }

        public Show(string Param)
        {
            InitializeComponent();
            TextBoxValue = Param;
        }

        private void textBoxShow_TextChanged(object sender, EventArgs e)
        {
            if (TextBoxChanged != null)
                TextBoxChanged(this, e);
        }
    }
}

6.最后效果:


你可能感兴趣的:(c#-winform)