You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C# Windows窗体在应用程序内以侧边栏形式重叠显示?

刚好做过类似的需求,要实现应用内部的侧边栏而不是全局的,核心是把Form2变成Form1的内嵌子窗体,下面给你具体的实现步骤和代码:

实现Windows Forms内部侧边栏的完整方案

1. 核心设置:将Form2转为Form1的子控件

在Form1的侧边栏按钮点击事件里,我们需要调整Form2的几个关键属性,让它能嵌入到Form1内部:

private void Sidebar_Click(object sender, EventArgs e)
{
    // 先检查是否已经创建过侧边栏,避免重复实例化
    var existingSidebar = this.Controls.OfType<Form2>().FirstOrDefault();
    if (existingSidebar != null)
    {
        // 切换显示/隐藏状态
        existingSidebar.Visible = !existingSidebar.Visible;
        return;
    }

    // 初始化侧边栏窗体
    Form2 sidebar = new Form2();
    sidebar.Owner = this; // 设置所有者为Form1,确保它随Form1最小化/关闭
    sidebar.TopLevel = false; // 必须设为false,才能作为子控件嵌入
    sidebar.FormBorderStyle = FormBorderStyle.None; // 去掉窗体边框,更像侧边栏
    sidebar.Dock = DockStyle.Left; // 停靠在Form1左侧
    sidebar.Size = new Size(250, this.ClientSize.Height); // 自定义宽度,高度匹配Form1客户端区域
    this.Controls.Add(sidebar); // 将侧边栏添加到Form1的控件集合
    sidebar.Show();
}

2. 优化适配:让侧边栏跟随Form1尺寸变化

如果Form1的大小会改变,我们可以绑定Form1的Resize事件,让侧边栏自动同步高度:

// 在Form1的构造函数中添加事件绑定
public Form1()
{
    InitializeComponent();
    this.Resize += Form1_Resize;
}

private void Form1_Resize(object sender, EventArgs e)
{
    var sidebar = this.Controls.OfType<Form2>().FirstOrDefault();
    if (sidebar != null && sidebar.Visible)
    {
        sidebar.Height = this.ClientSize.Height;
    }
}

3. 额外样式优化(可选)

如果想要更美观的侧边栏效果,可以做这些调整:

  • 给Form2添加背景色:设置BackColor = Color.FromArgb(240,240,240),和Form1区分开
  • 绘制侧边栏右侧的分隔线:在Form2的Paint事件里添加代码:
private void Form2_Paint(object sender, PaintEventArgs e)
{
    // 绘制右侧灰色分隔线
    e.Graphics.DrawLine(Pens.LightGray, this.Width - 1, 0, this.Width - 1, this.Height);
}

关键注意点

  • 必须设置TopLevel = false:这是让Form2能作为子控件嵌入的核心,否则无法添加到Form1的Controls集合
  • 不要设置StartPosition:让窗体自动跟随停靠布局,避免位置错乱
  • 用Owner属性关联Form1:确保侧边栏会随Form1一起最小化、关闭,不会单独留在任务栏

内容的提问来源于stack exchange,提问作者Eric Brown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:35:01