防止自定义边框大小调整手柄将Winform的大小调整得太小

时间:2018-06-23 22:52:54

标签: c# winforms border window-resize

我目前正忙于开发无边界WinForms表单,而我刚从here获得了一些代码。我根据自己的需要对其进行了修改,但现在遇到了麻烦。我将如何限制其调整大小?

当前,我可以调整窗口大小,使其仅是屏幕上的一个点。如何在最小尺寸上加一个“上限”?

以下是用于调整大小的代码片段(应按原样工作):

//Initializes the form
public Form1()
{
    InitializeComponent();
    this.DoubleBuffered = true;
    this.SetStyle(ControlStyles.ResizeRedraw, true);
}
private const int cGrip = 16;      // Grip size
private const int cCaption = 32;   // Caption bar height;

//Overides what happens everytime the form is drawn
protected override void OnPaint(PaintEventArgs e)
{
    //Draws a border with defined width
    int width = 1;
    Pen drawPen = new Pen(titleBar.BackColor, width);
    e.Graphics.DrawRectangle(drawPen, new Rectangle(width / 2, width / 2, this.Width - width, this.Height - width));
    drawPen.Dispose();

    //Draws the resizer grip
    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.Coral, rc);


}

//Handles windows messages
protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x84)
    {  // Trap WM_NCHITTEST
        Point pos = new Point(m.LParam.ToInt32());
        pos = this.PointToClient(pos);
        //if (pos.Y < cCaption)
        //{
        //    m.Result = (IntPtr)2;  // HTCAPTION
        //    return;
        //}
        if (
            pos.X >= this.ClientSize.Width - cGrip && 
            pos.Y >= this.ClientSize.Height - cGrip)
        {
            m.Result = (IntPtr)17; // HTBOTTOMRIGHT
            return;
        }
    }
    base.WndProc(ref m);
}

请注意,我不是一个经验丰富的C#程序员。我以前在C#中唯一的经验是在Unity中编程,因此,如果您能给我详细说明您可能拥有的解决方案的话,将不胜感激。

1 个答案:

答案 0 :(得分:0)

无论表单是否是无边界的,您仍然可以使用MinimumSizeMaximumSize属性。

尝试一下:

public Form1()
{
    InitializeComponent();
    this.DoubleBuffered = true;
    this.SetStyle(ControlStyles.ResizeRedraw, true);

    this.MinimumSize = new Size(200, 200);
    this.MaximumSize = new Size(800, 600);
}