一、重写窗体的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); } } }