Vertically (only) resizable windows form in C#

前端 未结 6 1517
时光取名叫无心
时光取名叫无心 2020-12-04 14:55

I have a situation where it would be beneficial to me to allow my windows form to be resized by the user, but only vertically. After some searching, it seems like there isn\

相关标签:
6条回答
  • 2020-12-04 15:04

    Let the FormBorderStyle to Resizable and set MaximumSize and MinimumSize = new Size(this.Width, 0)

    Correction:

    this.MinimumSize = new Size(this.Width, 0);
    this.MaximumSize = new Size(this.Width, Int32.MaxValue);
    
    0 讨论(0)
  • 2020-12-04 15:07

    Just an idea...

    public partial class Form1 : Form {
        int _width;
    
        public Form1() {
            _width = this.Width;
            InitializeComponent();
        }
    
        protected override void OnResize(EventArgs e) {
            this.Width = _width;
            base.OnResize(e);
        }
    }
    

    EDIT: please note that the min/max size solutions work much better than this hack :)

    0 讨论(0)
  • 2020-12-04 15:12

    To avoid the "rubber-banding" effect of @orsogufo's solution:

    public Form1()
    {
        InitializeComponent();
        this.MinimumSize = new Size(500, 0);
        this.MaximumSize = new Size(500, Screen.AllScreens.Max(s => s.Bounds.Height));
    }
    

    It won't correctly adjust its maximum height to accommodate a larger screen if you resize the screen bounds, but for static screen sizes it works great.

    0 讨论(0)
  • 2020-12-04 15:16

    Yes, it is possible. Just set your form.MinimumSize.Width = form.MaximumSize.Width = 100 (or whatever width you want).

    0 讨论(0)
  • 2020-12-04 15:19

    Set the max & min size for the width of the form only.

    0 讨论(0)
  • 2020-12-04 15:23

    You need to set the form's MinimumSize and MaximumSize properties to two sizes with different heights but equal widths.

    If you don't want the horizontal resize cursor to appear at all, you'll need to handle the WM_NCHITTEST message, like this:

    protected override void WndProc(ref Message m) {
        base.WndProc(ref m);
        switch (m.Msg) {
            case 0x84: //WM_NCHITTEST
                var result = (HitTest)m.Result.ToInt32();
                if (result == HitTest.Left || result == HitTest.Right)
                    m.Result = new IntPtr((int)HitTest.Caption);
                if (result == HitTest.TopLeft || result == HitTest.TopRight)
                    m.Result = new IntPtr((int)HitTest.Top);
                if (result == HitTest.BottomLeft || result == HitTest.BottomRight)
                    m.Result = new IntPtr((int)HitTest.Bottom);
    
                break;
        }
    }
    enum HitTest {
        Caption = 2,
        Transparent = -1,
        Nowhere = 0,
        Client = 1,
        Left = 10,
        Right = 11,
        Top = 12,
        TopLeft = 13,
        TopRight = 14,
        Bottom = 15,
        BottomLeft = 16,
        BottomRight = 17,
        Border = 18
    }
    
    0 讨论(0)
提交回复
热议问题