Home >Backend Development >C++ >How to Create Resizable Borderless Forms in Windows Forms?

How to Create Resizable Borderless Forms in Windows Forms?

Susan Sarandon
Susan SarandonOriginal
2025-01-11 13:01:40413browse

How to Create Resizable Borderless Forms in Windows Forms?

Create a borderless form: both beautiful and resizable

When designing custom form interfaces, developers usually prefer a simple borderless appearance. Although Windows provides an easy way to remove the default borders via the "FormBorderStyle" property, this results in the form not being resizable.

To overcome this limitation, let’s explore a comprehensive code solution that allows for borderless aesthetics and seamless resizing capabilities at the same time:

<code class="language-csharp">public partial class Form1 : Form {
    // 取消默认边框
    public Form1() {
        InitializeComponent();
        this.FormBorderStyle = FormBorderStyle.None;

        // 优化标志,提升响应速度和美观性
        this.DoubleBuffered = true;
        this.SetStyle(ControlStyles.ResizeRedraw, true);
    }

    // 抓取区域和标题栏尺寸常量
    private const int cGrip = 16;
    private const int cCaption = 32;

    // 自定义绘制抓取指示器
    protected override void OnPaint(PaintEventArgs e) {
        // 在右下角绘制调整大小的抓取区域
        Rectangle rc = new Rectangle(this.ClientSize.Width - cGrip, this.ClientSize.Height - cGrip, cGrip, cGrip);
        ControlPaint.DrawSizeGrip(e.Graphics, this.BackColor, rc);

        // 通过填充特定颜色的区域来模拟标题栏
        rc = new Rectangle(0, 0, this.ClientSize.Width, cCaption);
        e.Graphics.FillRectangle(Brushes.DarkBlue, rc);
    }

    // 拦截 WM_NCHITTEST 消息以实现自定义调整大小行为
    protected override void WndProc(ref Message m) {
        if (m.Msg == 0x84) {  // 捕获 WM_NCHITTEST 消息
            Point pos = new Point(m.LParam.ToInt32());
            pos = this.PointToClient(pos);

            // 判断鼠标光标是否在模拟标题栏内
            if (pos.X >= this.ClientSize.Width - cGrip && pos.Y >= this.ClientSize.Height - cGrip) {
                m.Result = (IntPtr)17; // HTBOTTOMRIGHT
                return;
            }
        }

        // 将未处理的消息传递给基类进行默认处理
        base.WndProc(ref m);
    }
}</code>

By implementing this code in your borderless form, you can effectively enable resizing functionality while maintaining the desired aesthetics. A simulated title bar and custom grab indicators provide an intuitive and full-featured user experience, allowing users to easily resize forms.

The above is the detailed content of How to Create Resizable Borderless Forms in Windows Forms?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn