从中心调整大小[Winforms]

时间:2017-04-19 17:23:45

标签: c# winforms resize window-resize

我有两种形式(父母和孩子)
子表单的属性为ControlBox:FalseDoubleBuffer:True& FormBorderStyle:SizeableToolWindow(其余都是默认值)。
我希望子表单从中心调整大小(而不是从左上角调整大小)

在子格式Resize事件中,我有以下代码

this.Location = System.Drawing.Point(x / 2 - this.Width / 2, y / 2 - this.Height / 2);
//tried this.CenterToParent();`

其中x =父表格的宽度,y =父表格的高度。

现在在从父表单显示子表单后,调整大小时闪烁很多,子表单往往会回到原来的位置!
如何从中心创建平滑的调整大小?
有没有办法将Form的调整大小原因改为中心?
这个问题已经发布here,但没有理解解决方案

1 个答案:

答案 0 :(得分:1)

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnResize(EventArgs e)
        {
            this.Location = new System.Drawing.Point(this.Location.X / 2 - this.Width / 2, this.Location.Y / 2 - this.Height / 2);
            //tried this.CenterToParent();`
            base.OnResize(e);
        }

        const int WM_SYSCOMMAND = 0x112;
        const int SC_MAXIMIZE = 0xF030;
        const int SC_MAXIMIZE2 = 0xF032;

        protected override void WndProc(ref Message m)
        {
            if ((m.Msg == WM_SYSCOMMAND && m.WParam == new IntPtr(SC_MAXIMIZE)) || m.WParam == new IntPtr(SC_MAXIMIZE2))
            {
                this.Size = this.MaximumSize;
                m.Result = new IntPtr(0);
                //base.WndProc(ref m);
                //Eat the message so won't process further
            }
            else
            {
                m.Result = new IntPtr(0);
                base.WndProc(ref m);
            }
        }
    }
}

这是更好的链接: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.wndproc(v=vs.110).aspx