LOGO 首页 OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 技术文档 其他文档  
 
网站管理员

C# WinForm 窗体之间传值方式

admin
2026年11月26日 21:56 本文热度 191

一、方式1(直接属性赋值)

1. 原理:子窗体暴露public属性,父窗体持有子窗体实例直接读写,子窗体持有父窗体引用反向写数据;

2. 源码

WinFormDemo1.cs

using System;using System.Windows.Forms;
namespace WinFormDemo{    //子窗体    public class FormChild : Form    {        public string ReceiveData { get; set; }        public FormMain ParentRef { get; set; }
        public FormChild()        {            this.Text = "子窗体 - 属性赋值";            this.Size = new System.Drawing.Size(300, 180);            Button btnBack = new Button { Text = "回传数据", Location = new System.Drawing.Point(80, 60) };            btnBack.Click += (s, e) =>            {                if (ParentRef != null)                {                    ParentRef.ResultVal = "子窗体通过属性回传";                }                this.Close();            };            this.Controls.Add(btnBack);            this.Load += (s, e) => MessageBox.Show("收到父窗体:" + ReceiveData);        }    }
    //主窗体    public class FormMain : Form    {        public string ResultVal { get; set; }        public FormMain()        {            this.Text = "主窗体 - 属性赋值";            this.Size = new System.Drawing.Size(400, 220);            Button btnOpen = new Button { Text = "打开子窗体", Location = new System.Drawing.Point(100, 80) };            btnOpen.Click += (s, e) =>            {                FormChild child = new FormChild();                child.ReceiveData = "父窗体发给子窗体";                child.ParentRef = this;                child.ShowDialog();                MessageBox.Show("主窗体收到回写:" + ResultVal);            };            this.Controls.Add(btnOpen);        }
        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.Run(new FormMain());        }    }}

3. 编译

csc /r:System.Windows.Forms.dll WinFormDemo1.cs

4. 程序运行效果

二、方式2(构造函数传参,单向初始化)

1. 原理:打开子窗体时,通过构造传入初始数据,子窗体只读,不支持回传;

2. 源码

WinFormDemo2.cs 

using System;using System.Windows.Forms;
namespace WinFormDemo{    public class FormChild : Form    {        public string InitMsg { get; }        //带参构造        public FormChild(string msg)        {            InitMsg = msg;            this.Text = "子窗体 - 构造传参";            this.Size = new System.Drawing.Size(300, 180);            this.Load += (s, e) => MessageBox.Show("构造收到:" + InitMsg);        }    }
    public class FormMain : Form    {        public FormMain()        {            this.Text = "主窗体 - 构造传参";            this.Size = new System.Drawing.Size(400, 220);            Button btnOpen = new Button { Text = "打开子窗体", Location = new System.Drawing.Point(100, 80) };            btnOpen.Click += (s, e) =>            {                FormChild child = new FormChild("构造函数传入的初始数据");                child.ShowDialog();            };            this.Controls.Add(btnOpen);        }
        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.Run(new FormMain());        }    }}

3. 编译

csc /r:System.Windows.Forms.dll WinFormDemo2.cs

4. 程序运行效果

三、方式3(事件回调)

1. 原理:子窗体定义事件向外抛数据,父窗体订阅事件接收,子窗体不知道是谁订阅(低耦合);

2. 源码

WinFormDemo3.cs 

using System;using System.Windows.Forms;
namespace WinFormDemo{    public class FormChild : Form    {        //委托 + 事件        public delegate void DataReturnHandler(string data);        public event DataReturnHandler OnDataReturn;
        public FormChild()        {            this.Text = "子窗体 - 事件回调";            this.Size = new System.Drawing.Size(300, 180);            Button btnSend = new Button { Text = "事件回传", Location = new System.Drawing.Point(80, 60) };            btnSend.Click += (s, e) =>            {                OnDataReturn?.Invoke("子窗体通过事件回传内容");                this.Close();            };            this.Controls.Add(btnSend);        }    }
    public class FormMain : Form    {        public FormMain()        {            this.Text = "主窗体 - 事件回调";            this.Size = new System.Drawing.Size(400, 220);            Button btnOpen = new Button { Text = "打开子窗体", Location = new System.Drawing.Point(100, 80) };            btnOpen.Click += (s, e) =>            {                FormChild child = new FormChild();                // 订阅                child.OnDataReturn += Child_OnDataReturn;                child.ShowDialog();                // 取消订阅!                child.OnDataReturn -= Child_OnDataReturn;            };            this.Controls.Add(btnOpen);        }
        private void Child_OnDataReturn(string msg)        {            MessageBox.Show("主窗体收到事件:" + msg);        }
        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.Run(new FormMain());        }    }}

3. 编译

csc /r:System.Windows.Forms.dll WinFormDemo3.cs

4. 程序运行效果

四、方式4(全局消息总线/Mediator 中介者)

1. 原理:独立单例消息中心,发布者、订阅者互不感知,适合多窗体广播;

2. 源码

WinFormDemo4.cs 

using System;using System.Collections.Generic;using System.Windows.Forms;
// 消息总线public static class MessageBus{    //泛型委托    private static readonly Dictionary<Type, Delegate> _subscribers = new Dictionary<Type, Delegate>();
    public static void Subscribe<T>(Action<T> handler)    {        Type t = typeof(T);        if (!_subscribers.ContainsKey(t))        {            _subscribers[t] = handler;        }        else        {            _subscribers[t] = Delegate.Combine(_subscribers[t], handler);        }    }
    public static void UnSubscribe<T>(Action<T> handler)    {        Type t = typeof(T);        if (_subscribers.ContainsKey(t))        {            Delegate d = Delegate.Remove(_subscribers[t], handler);            if (d == null)                _subscribers.Remove(t);            else                _subscribers[t] = d;        }    }
    public static void Publish<T>(T message)    {        Type t = typeof(T);        if (_subscribers.ContainsKey(t))        {            Action<T> action = _subscribers[t] as Action<T>;            if (action != null)                action(message);        }    }}
// 定义消息实体(强类型,推荐)public class TextMsg{    public string Content { get; set; }}
//主窗体 Form1public class Form1 : Form{    private Button btnOpen;    private Label lblRecv;
    public Form1()    {        this.Text = "主窗体 - 总线发布";        this.Size = new System.Drawing.Size(400, 200);        btnOpen = new Button { Text = "打开子窗体", Location = new System.Drawing.Point(20, 20) };        lblRecv = new Label { Text = "等待消息...", Location = new System.Drawing.Point(20, 70), AutoSize = true };        this.Controls.Add(btnOpen);        this.Controls.Add(lblRecv);
        // 订阅消息        MessageBus.Subscribe<TextMsg>(OnMsg);        btnOpen.Click += (s, e) =>        {            Form2 f2 = new Form2();            f2.Show();        };    }
    private void OnMsg(TextMsg msg)    {        // 跨线程安全        if (lblRecv.InvokeRequired)        {            lblRecv.Invoke(new Action(() => OnMsg(msg)));            return;        }        lblRecv.Text = "收到:" + msg.Content;    }
    protected override void Dispose(bool disposing)    {        if (disposing)        {            MessageBus.UnSubscribe<TextMsg>(OnMsg);        }        base.Dispose(disposing);    }}
//子窗体 Form2public class Form2 : Form{    private TextBox txtInput;    private Button btnSend;
    public Form2()    {        this.Text = "子窗体 - 总线发送";        this.Size = new System.Drawing.Size(300, 180);        txtInput = new TextBox { Location = new System.Drawing.Point(20, 20), Width = 200 };        btnSend = new Button { Text = "发消息给主窗体", Location = new System.Drawing.Point(20, 60) };        this.Controls.Add(txtInput);        this.Controls.Add(btnSend);
        btnSend.Click += (s, e) =>        {            if (!string.IsNullOrEmpty(txtInput.Text))            {                MessageBus.Publish(new TextMsg { Content = txtInput.Text });            }        };    }}
//程序入口static class Program{    [STAThread]    static void Main()    {        Application.EnableVisualStyles();        Application.SetCompatibleTextRenderingDefault(false);        Application.Run(new Form1());    }}

3. 编译

csc /r:System.Windows.Forms.dll WinFormDemo4.cs

4. 程序运行效果

五、方式5(静态变量传值)

1. 原理:静态类共享数据,所有窗体直接读写静态字段;

2. 源码

WinFormDemo5.cs 

using System;using System.Windows.Forms;
namespace WinFormDemo{    //静态共享容器    public static class GlobalShare    {        public static string TextData { get; set; }    }
    public class FormChild : Form    {        public FormChild()        {            this.Text = "子窗体 - 静态变量";            this.Size = new System.Drawing.Size(300, 180);            this.Load += (s, e) => MessageBox.Show("读取静态变量:" + GlobalShare.TextData);            Button btnModify = new Button { Text = "修改静态变量", Location = new System.Drawing.Point(60, 60) };            btnModify.Click += (s, e) =>            {                GlobalShare.TextData = "子窗体修改静态值";                this.Close();            };            this.Controls.Add(btnModify);        }    }
    public class FormMain : Form    {        public FormMain()        {            this.Text = "主窗体 - 静态变量";            this.Size = new System.Drawing.Size(400, 220);            Button btnOpen = new Button { Text = "打开子窗体", Location = new System.Drawing.Point(100, 80) };            btnOpen.Click += (s, e) =>            {                GlobalShare.TextData = "主窗体写入静态数据";                FormChild child = new FormChild();                child.ShowDialog();                MessageBox.Show("静态变量最新:" + GlobalShare.TextData);            };            this.Controls.Add(btnOpen);        }
        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.Run(new FormMain());        }    }}

3. 编译

csc /r:System.Windows.Forms.dll WinFormDemo5.cs

4. 程序运行效果

六、几种方式对比


阅读原文:原文链接


该文章在 2026/11/27 11:41:25 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2026 ClickSun All Rights Reserved  粤ICP备13012886号-9  粤公网安备44030602007207号