WinForms 桌面应用程序

发布于:2025-07-22 ⋅ 阅读:(14) ⋅ 点赞:(0)
// ========== Program.cs ==========
using System;
using System.Windows.Forms;

namespace MultiWindowApp
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }

    // ========== 消息传递委托和事件参数 ==========
    public delegate void MessageEventHandler(object sender, MessageEventArgs e);

    public class MessageEventArgs : EventArgs
    {
        public string Message { get; set; }
        public string SenderName { get; set; }

        public MessageEventArgs(string message, string senderName)
        {
            Message = message;
            SenderName = senderName;
        }
    }

    // ========== 窗体管理器 ==========
    public static class FormManager
    {
        private static System.Collections.Generic.Dictionary<string, BaseChildForm> childForms = 
            new System.Collections.Generic.Dictionary<string, BaseChildForm>();

        public static void RegisterChildForm(string name, BaseChildForm form)
        {
            if (!childForms.ContainsKey(name))
            {
                childForms.Add(name, form);
            }
        }

        public static void UnregisterChildForm(string name)
        {
            if (childForms.ContainsKey(name))
            {
                childForms.Remove(name);
            }
        }

        public static BaseChildForm GetChildForm(string name)
        {
            return childForms.ContainsKey(name) ? childForms[name] : null;
        }

        public static System.Collections.Generic.List<string> GetChildFormNames()
        {
            return new System.Collections.Generic.List<string>(childForms.Keys);
        }
    }

    // ========== MainForm.cs ==========
    public partial class MainForm : Form
    {
        private HomeForm homeForm;
        private UserManageForm userForm;
        private SettingsForm settingsForm;
        private Form currentForm;
        private int childFormCount = 0;

        public MainForm()
        {
            InitializeComponent();
            InitializeForms();
        }

        private void InitializeComponent()
        {
            // 窗体设置
            this.Text = "多窗体通信示例程序";
            this.Size = new System.Drawing.Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;

            // StatusStrip
            this.statusStrip1 = new StatusStrip();
            this.toolStripStatusLabel1 = new ToolStripStatusLabel();
            this.statusStrip1.Items.Add(this.toolStripStatusLabel1);
            this.Controls.Add(this.statusStrip1);

            // 左侧菜单面板
            this.panelMenu = new Panel();
            this.panelMenu.Dock = DockStyle.Left;
            this.panelMenu.Width = 150;
            this.panelMenu.BackColor = System.Drawing.Color.LightGray;

            // 菜单按钮
            this.btnHome = CreateMenuButton("主页", 0);
            this.btnUsers = CreateMenuButton("用户管理", 1);
            this.btnSettings = CreateMenuButton("设置", 2);
            this.btnOpenChild = CreateMenuButton("打开子窗口", 3);

            this.panelMenu.Controls.Add(this.btnHome);
            this.panelMenu.Controls.Add(this.btnUsers);
            this.panelMenu.Controls.Add(this.btnSettings);
            this.panelMenu.Controls.Add(this.btnOpenChild);

            // 右侧内容面板
            this.panelContent = new Panel();
            this.panelContent.Dock = DockStyle.Fill;
            this.panelContent.BackColor = System.Drawing.Color.White;

            this.Controls.Add(this.panelContent);
            this.Controls.Add(this.panelMenu);

            // 事件绑定
            this.btnHome.Click += BtnHome_Click;
            this.btnUsers.Click += BtnUsers_Click;
            this.btnSettings.Click += BtnSettings_Click;
            this.btnOpenChild.Click += BtnOpenChild_Click;
        }

        private Button CreateMenuButton(string text, int index)
        {
            Button btn = new Button();
            btn.Text = text;
            btn.Dock = DockStyle.Top;
            btn.Height = 40;
            btn.FlatStyle = FlatStyle.Flat;
            btn.FlatAppearance.BorderSize = 0;
            btn.Top = index * 40;
            return btn;
        }

        private void InitializeForms()
        {
            homeForm = new HomeForm();
            userForm = new UserManageForm();
            settingsForm = new SettingsForm();

            // 默认显示主页
            ShowFormInPanel(homeForm);
        }

        private void ShowFormInPanel(Form form)
        {
            if (currentForm != null)
            {
                currentForm.Hide();
            }

            form.TopLevel = false;
            form.FormBorderStyle = FormBorderStyle.None;
            form.Dock = DockStyle.Fill;
            
            if (!panelContent.Controls.Contains(form))
            {
                panelContent.Controls.Add(form);
            }
            
            form.Show();
            currentForm = form;
            UpdateStatus("当前页面: " + form.Text);
        }

        private void BtnHome_Click(object sender, EventArgs e)
        {
            ShowFormInPanel(homeForm);
        }

        private void BtnUsers_Click(object sender, EventArgs e)
        {
            ShowFormInPanel(userForm);
        }

        private void BtnSettings_Click(object sender, EventArgs e)
        {
            ShowFormInPanel(settingsForm);
        }

        private void BtnOpenChild_Click(object sender, EventArgs e)
        {
            childFormCount++;
            BaseChildForm childForm = (childFormCount % 2 == 1) ? 
                (BaseChildForm)new ChildForm1() : (BaseChildForm)new ChildForm2();
            
            childForm.WindowName = "子窗口" + childFormCount;
            childForm.MainForm = this;
            childForm.MessageReceived += ChildForm_MessageReceived;
            childForm.Show();
        }

        private void ChildForm_MessageReceived(object sender, MessageEventArgs e)
        {
            UpdateStatus(string.Format("收到来自 {0} 的消息: {1}", e.SenderName, e.Message));
        }

        public void UpdateStatus(string message)
        {
            toolStripStatusLabel1.Text = message;
        }

        // 控件声明
        private Panel panelMenu;
        private Panel panelContent;
        private Button btnHome;
        private Button btnUsers;
        private Button btnSettings;
        private Button btnOpenChild;
        private StatusStrip statusStrip1;
        private ToolStripStatusLabel toolStripStatusLabel1;
    }

    // ========== BaseChildForm.cs ==========
    public partial class BaseChildForm : Form
    {
        public event MessageEventHandler MessageReceived;
        public MainForm MainForm { get; set; }
        public string WindowName { get; set; }

        public BaseChildForm()
        {
            InitializeComponent();
        }

        protected virtual void InitializeComponent()
        {
            // 窗体设置
            this.Size = new System.Drawing.Size(400, 300);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 窗口名称标签
            this.lblWindowName = new Label();
            this.lblWindowName.Location = new System.Drawing.Point(12, 12);
            this.lblWindowName.Size = new System.Drawing.Size(200, 20);

            // 消息文本框
            this.txtMessage = new TextBox();
            this.txtMessage.Location = new System.Drawing.Point(12, 40);
            this.txtMessage.Size = new System.Drawing.Size(360, 100);
            this.txtMessage.Multiline = true;
            this.txtMessage.ScrollBars = ScrollBars.Vertical;

            // 发送给父窗口按钮
            this.btnSendToParent = new Button();
            this.btnSendToParent.Location = new System.Drawing.Point(12, 150);
            this.btnSendToParent.Size = new System.Drawing.Size(120, 30);
            this.btnSendToParent.Text = "发送给父窗口";
            this.btnSendToParent.Click += BtnSendToParent_Click;

            // 子窗口列表
            this.cboChildWindows = new ComboBox();
            this.cboChildWindows.Location = new System.Drawing.Point(12, 190);
            this.cboChildWindows.Size = new System.Drawing.Size(150, 21);
            this.cboChildWindows.DropDownStyle = ComboBoxStyle.DropDownList;

            // 发送给其他子窗口按钮
            this.btnSendToOther = new Button();
            this.btnSendToOther.Location = new System.Drawing.Point(170, 190);
            this.btnSendToOther.Size = new System.Drawing.Size(120, 30);
            this.btnSendToOther.Text = "发送给子窗口";
            this.btnSendToOther.Click += BtnSendToOther_Click;

            // 添加控件
            this.Controls.Add(this.lblWindowName);
            this.Controls.Add(this.txtMessage);
            this.Controls.Add(this.btnSendToParent);
            this.Controls.Add(this.cboChildWindows);
            this.Controls.Add(this.btnSendToOther);

            // 窗体事件
            this.Load += BaseChildForm_Load;
            this.FormClosed += BaseChildForm_FormClosed;
        }

        private void BaseChildForm_Load(object sender, EventArgs e)
        {
            this.Text = WindowName;
            this.lblWindowName.Text = "窗口名称: " + WindowName;
            FormManager.RegisterChildForm(WindowName, this);
            RefreshChildWindowsList();
        }

        private void BaseChildForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            FormManager.UnregisterChildForm(WindowName);
        }

        private void BtnSendToParent_Click(object sender, EventArgs e)
        {
            if (MainForm != null)
            {
                string message = "来自" + WindowName + "的消息: " + DateTime.Now.ToString();
                MainForm.UpdateStatus(message);
                AddMessage("已发送消息给父窗口");
            }
        }

        private void BtnSendToOther_Click(object sender, EventArgs e)
        {
            if (cboChildWindows.SelectedItem != null)
            {
                string targetName = cboChildWindows.SelectedItem.ToString();
                BaseChildForm targetForm = FormManager.GetChildForm(targetName);
                
                if (targetForm != null)
                {
                    string message = "来自" + WindowName + "的消息: " + DateTime.Now.ToString();
                    targetForm.ReceiveMessage(message, WindowName);
                    AddMessage("已发送消息给: " + targetName);
                }
            }
        }

        public void ReceiveMessage(string message, string senderName)
        {
            AddMessage(string.Format("[{0}] {1}: {2}", 
                DateTime.Now.ToString("HH:mm:ss"), senderName, message));
            
            if (MessageReceived != null)
            {
                MessageReceived(this, new MessageEventArgs(message, senderName));
            }
        }

        protected void AddMessage(string message)
        {
            txtMessage.AppendText(message + Environment.NewLine);
        }

        protected void RefreshChildWindowsList()
        {
            cboChildWindows.Items.Clear();
            foreach (string name in FormManager.GetChildFormNames())
            {
                if (name != WindowName)
                {
                    cboChildWindows.Items.Add(name);
                }
            }
            if (cboChildWindows.Items.Count > 0)
            {
                cboChildWindows.SelectedIndex = 0;
            }
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
            RefreshChildWindowsList();
        }

        // 控件声明
        protected TextBox txtMessage;
        protected Button btnSendToParent;
        protected Button btnSendToOther;
        protected ComboBox cboChildWindows;
        protected Label lblWindowName;
    }

    // ========== ChildForm1.cs ==========
    public class ChildForm1 : BaseChildForm
    {
        public ChildForm1()
        {
            this.BackColor = System.Drawing.Color.LightBlue;
        }
    }

    // ========== ChildForm2.cs ==========
    public class ChildForm2 : BaseChildForm
    {
        public ChildForm2()
        {
            this.BackColor = System.Drawing.Color.LightGreen;
        }
    }

    // ========== HomeForm.cs ==========
    public partial class HomeForm : Form
    {
        public HomeForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.Text = "主页";

            // 欢迎标签
            this.lblWelcome = new Label();
            this.lblWelcome.Text = "欢迎使用多窗体通信示例程序";
            this.lblWelcome.Font = new System.Drawing.Font("微软雅黑", 16F, System.Drawing.FontStyle.Bold);
            this.lblWelcome.Location = new System.Drawing.Point(50, 50);
            this.lblWelcome.Size = new System.Drawing.Size(400, 40);

            // 图片框
            this.pictureBox1 = new PictureBox();
            this.pictureBox1.Location = new System.Drawing.Point(50, 100);
            this.pictureBox1.Size = new System.Drawing.Size(200, 200);
            this.pictureBox1.BorderStyle = BorderStyle.FixedSingle;

            // 信息标签
            this.lblInfo = new Label();
            this.lblInfo.Text = "这是一个演示多窗体间通信的示例程序。\n" +
                              "• 支持父子窗体通信\n" +
                              "• 支持子窗体间通信\n" +
                              "• 支持Panel内嵌窗体切换";
            this.lblInfo.Location = new System.Drawing.Point(270, 100);
            this.lblInfo.Size = new System.Drawing.Size(300, 100);

            this.Controls.Add(this.lblWelcome);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.lblInfo);
        }

        private Label lblWelcome;
        private PictureBox pictureBox1;
        private Label lblInfo;
    }

    // ========== UserManageForm.cs ==========
    public partial class UserManageForm : Form
    {
        public UserManageForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.Text = "用户管理";

            // 搜索框
            this.txtSearch = new TextBox();
            this.txtSearch.Location = new System.Drawing.Point(12, 12);
            this.txtSearch.Size = new System.Drawing.Size(200, 21);

            // 数据表格
            this.dataGridView1 = new DataGridView();
            this.dataGridView1.Location = new System.Drawing.Point(12, 40);
            this.dataGridView1.Size = new System.Drawing.Size(500, 300);
            this.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Columns.Add("ID", "ID");
            this.dataGridView1.Columns.Add("Name", "姓名");
            this.dataGridView1.Columns.Add("Email", "邮箱");

            // 按钮
            this.btnAdd = new Button();
            this.btnAdd.Location = new System.Drawing.Point(520, 40);
            this.btnAdd.Size = new System.Drawing.Size(75, 23);
            this.btnAdd.Text = "添加";

            this.btnEdit = new Button();
            this.btnEdit.Location = new System.Drawing.Point(520, 70);
            this.btnEdit.Size = new System.Drawing.Size(75, 23);
            this.btnEdit.Text = "编辑";

            this.btnDelete = new Button();
            this.btnDelete.Location = new System.Drawing.Point(520, 100);
            this.btnDelete.Size = new System.Drawing.Size(75, 23);
            this.btnDelete.Text = "删除";

            this.Controls.Add(this.txtSearch);
            this.Controls.Add(this.dataGridView1);
            this.Controls.Add(this.btnAdd);
            this.Controls.Add(this.btnEdit);
            this.Controls.Add(this.btnDelete);

            // 添加示例数据
            this.dataGridView1.Rows.Add("1", "张三", "zhangsan@example.com");
            this.dataGridView1.Rows.Add("2", "李四", "lisi@example.com");
        }

        private DataGridView dataGridView1;
        private Button btnAdd;
        private Button btnEdit;
        private Button btnDelete;
        private TextBox txtSearch;
    }

    // ========== SettingsForm.cs ==========
    public partial class SettingsForm : Form
    {
        public SettingsForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.Text = "设置";

            // 设置组
            this.groupBox1 = new GroupBox();
            this.groupBox1.Text = "常规设置";
            this.groupBox1.Location = new System.Drawing.Point(12, 12);
            this.groupBox1.Size = new System.Drawing.Size(300, 150);

            // 复选框
            this.chkAutoStart = new CheckBox();
            this.chkAutoStart.Text = "开机自动启动";
            this.chkAutoStart.Location = new System.Drawing.Point(20, 30);
            this.chkAutoStart.Size = new System.Drawing.Size(150, 20);

            this.chkMinimize = new CheckBox();
            this.chkMinimize.Text = "最小化到系统托盘";
            this.chkMinimize.Location = new System.Drawing.Point(20, 60);
            this.chkMinimize.Size = new System.Drawing.Size(150, 20);

            this.groupBox1.Controls.Add(this.chkAutoStart);
            this.groupBox1.Controls.Add(this.chkMinimize);

            // 按钮
            this.btnSave = new Button();
            this.btnSave.Location = new System.Drawing.Point(156, 180);
            this.btnSave.Size = new System.Drawing.Size(75, 23);
            this.btnSave.Text = "保存";

            this.btnCancel = new Button();
            this.btnCancel.Location = new System.Drawing.Point(237, 180);
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.Text = "取消";

            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.btnSave);
            this.Controls.Add(this.btnCancel);
        }

        private GroupBox groupBox1;
        private CheckBox chkAutoStart;
        private CheckBox chkMinimize;
        private Button btnSave;
        private Button btnCancel;
    }
}

需要创建的窗体和控件

1. 主窗体 (MainForm)

需要拖入的控件:

  • Panel (name: panelMenu) - 左侧菜单面板
    • Button (name: btnHome) - 主页按钮
    • Button (name: btnUsers) - 用户管理按钮
    • Button (name: btnSettings) - 设置按钮
    • Button (name: btnOpenChild) - 打开子窗口按钮
  • Panel (name: panelContent) - 右侧内容面板
  • StatusStrip (name: statusStrip1)
    • ToolStripStatusLabel (name: toolStripStatusLabel1)

2. 基础子窗体 (BaseChildForm)

需要拖入的控件:

  • TextBox (name: txtMessage) - 用于显示接收的消息
  • Button (name: btnSendToParent) - 发送消息给父窗口
  • Button (name: btnSendToOther) - 发送消息给其他子窗口
  • ComboBox (name: cboChildWindows) - 选择目标子窗口
  • Label (name: lblWindowName) - 显示窗口名称

3. 内嵌窗体 (用于在主窗体Panel中显示)

HomeForm

需要拖入的控件:

  • Label (name: lblWelcome) - 欢迎标签
  • PictureBox (name: pictureBox1) - 显示图片
  • Label (name: lblInfo) - 信息标签
UserManageForm

需要拖入的控件:

  • DataGridView (name: dataGridView1) - 用户列表
  • Button (name: btnAdd) - 添加用户
  • Button (name: btnEdit) - 编辑用户
  • Button (name: btnDelete) - 删除用户
  • TextBox (name: txtSearch) - 搜索框
SettingsForm

需要拖入的控件:

  • GroupBox (name: groupBox1) - 设置组
    • CheckBox (name: chkAutoStart) - 自动启动
    • CheckBox (name: chkMinimize) - 最小化到托盘
  • Button (name: btnSave) - 保存设置
  • Button (name: btnCancel) - 取消

4. 子窗体实例 (继承自BaseChildForm)

  • ChildForm1
  • ChildForm2

完整代码实现## 程序功能说明

主要功能实现:

  1. 主窗体 (MainForm)

    • 左侧菜单栏,可切换不同功能页面
    • 右侧内容区域,通过Panel嵌入不同的窗体
    • 状态栏显示实时消息
    • 可创建多个子窗口
  2. 窗体间通信机制

    • 使用事件委托实现消息传递
    • FormManager 类管理所有子窗体实例
    • 支持父窗体与子窗体双向通信
    • 支持子窗体之间的通信
  3. 继承关系

    • BaseChildForm 作为基类,定义了通用的通信功能
    • ChildForm1 和 ChildForm2 继承自 BaseChildForm
    • 不同的子窗体可以有不同的背景色或特定功能
  4. Panel 内嵌窗体切换

    • HomeForm、UserManageForm、SettingsForm 可在主窗体的 Panel 中切换显示
    • 实现了类似 MDI 的效果,但更加灵活

使用说明:

  1. 在 Visual Studio 2010 中创建新的 Windows Forms 应用程序
  2. 创建上述所有窗体类文件
  3. 根据说明在设计器中拖入相应的控件
  4. 将提供的代码复制到相应的文件中
  5. 编译运行程序

程序特点:

  • 完全兼容 .NET Framework 4.0
  • 使用基础的 WinForms 控件,无需第三方组件
  • 代码结构清晰,易于扩展
  • 实现了完整的桌面应用程序框架

网站公告

今日签到

点亮在社区的每一天
去签到