Winform窗体最大化的时候,如何指定窗体的位置、大小

一、重写窗体的SizeChanged事件不能改变窗体最大化的位置和大小。

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_SizeChanged(object sender, EventArgs e)
        {
            int height, width, newformx, newformy;
            height = System.Windows.Forms.SystemInformation.WorkingArea.Height;
            width = System.Windows.Forms.SystemInformation.WorkingArea.Width;
            switch (this.WindowState)
            {
                case FormWindowState.Maximized://最大化操作
                    this.Width = width;
                    this.Height = height - 50;
                    newformx = 0;
                    newformy = 50;
                    this.SetDesktopLocation(newformx, newformy);
                    break;
                case FormWindowState.Normal://默认窗口大小
                    this.Width = 808;
                    this.Height = 618;
                    newformx = 0;
                    newformy = 50;
                    this.SetDesktopLocation(newformx, newformy);
                    break;
            }
        }
    }

二、重写WndProc方法得以实现。

public partial class Form2 : Form
    {
        private const long WM_GETMINMAXINFO = 0x24;

        public struct PointAPI
        {
            public int x;
            public int y;
        }

        public struct MinMaxInfo
        {
            public PointAPI ptReserved;
            public PointAPI ptMaxSize;
            public PointAPI ptMaxPosition;
            public PointAPI ptMinTrackSize;
            public PointAPI ptMaxTrackSize;
        }

        public Form2()
        {
            InitializeComponent();
            this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
        }

        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == WM_GETMINMAXINFO)
            {
                MinMaxInfo mmi = (MinMaxInfo)m.GetLParam(typeof(MinMaxInfo));
                mmi.ptMinTrackSize.x = this.MinimumSize.Width;
                mmi.ptMinTrackSize.y = this.MinimumSize.Height;
                if (this.MaximumSize.Width != 0 || this.MaximumSize.Height != 0)
                {
                    mmi.ptMaxTrackSize.x = this.MaximumSize.Width;
                    mmi.ptMaxTrackSize.y = this.MaximumSize.Height;
                }
                mmi.ptMaxPosition.x = 1;
                mmi.ptMaxPosition.y = 1;
                System.Runtime.InteropServices.Marshal.StructureToPtr(mmi, m.LParam, true);
            }
        }
    }
作者:灬花儿灬
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/flower1990/p/5940991.html