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);
            }
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM