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

WinForm程序打开MDI窗体后移除左上角图标及上下文菜单

移除WinForm MDI窗体左上角的图标和菜单

问题描述

开发WinForm应用程序时,打开MDI窗体后左上角会显示图标,点击该图标会弹出系统菜单。尝试设置ShowIcon = false无效果;设置ControlBox = false会移除所有标题栏控件,但需要保留右上角的关闭按钮。

解决方案

方法一:重写WndProc拦截消息

在MDI窗体类中添加以下代码,通过拦截特定Windows消息实现隐藏图标、屏蔽菜单,同时保留关闭按钮:

protected override void WndProc(ref Message m)
{
    const int WM_GETICON = 0x007F;
    const int WM_NCLBUTTONDOWN = 0x00A1;
    const int WM_SYSCOMMAND = 0x0112;
    const int HTSYSMENU = 0x0003;
    const int SC_MOUSEMENU = 0xF090;
    const int SC_KEYMENU = 0xF080;

    if (m.Msg == WM_GETICON)
    {
        // 返回空图标,隐藏左上角图标
        m.Result = IntPtr.Zero;
        return;
    }
    else if (m.Msg == WM_NCLBUTTONDOWN && m.WParam.ToInt32() == HTSYSMENU)
    {
        // 拦截左上角图标区域的点击,阻止弹出菜单
        return;
    }
    else if (m.Msg == WM_SYSCOMMAND && (m.WParam.ToInt32() == SC_MOUSEMENU || m.WParam.ToInt32() == SC_KEYMENU))
    {
        // 屏蔽鼠标/键盘触发的系统菜单
        return;
    }
    base.WndProc(ref m);
}

方法二:结合API修改窗体样式

通过Windows API调整窗体样式,移除系统菜单关联的图标和菜单,同时保留关闭按钮:

  1. 先在窗体类中引入API:
using System.Runtime.InteropServices;

[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);

private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x00080000;
private const int WS_CAPTION = 0x00C00000;
  1. 在窗体Load事件中添加代码:
private void MdiForm_Load(object sender, EventArgs e)
{
    // 获取当前窗体样式,移除系统菜单样式但保留标题栏
    int currentStyle = GetWindowLong(this.Handle, GWL_STYLE);
    currentStyle &= ~WS_SYSMENU;
    currentStyle |= WS_CAPTION;
    SetWindowLong(this.Handle, GWL_STYLE, currentStyle);
    this.Refresh();
}

注意:需将窗体的ControlBox属性保持为true,才能保留右上角关闭按钮。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 12:47:01