开发者

Move form only vertically

How to create a WinF开发者_StackOverflow中文版orms form which will be moved by TitleBar only vertically?


You have to intercept the WM_MOVING notification message that Windows sends. Here's the code:

using System.Runtime.InteropServices;
...
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
        private struct RECT {
            public int left, top, right, bottom;
        }
        protected override void WndProc(ref Message m) {
            if (m.Msg == 0x216) {  // Trap WM_MOVING
                var rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
                int w = rc.right - rc.left;
                rc.left = this.Left;
                rc.right = rc.left + w;
                Marshal.StructureToPtr(rc, m.LParam, false);
            }
            base.WndProc(ref m);
        }
    }


This will do it (but it's not pretty) :

    private void MainForm_Move(object sender, EventArgs e)
    {
        this.Left = 100;
    }


You can shortcut the move operation by resetting the Location of your form to the initial X value and the Y value of the move. This solution is simple, but will flicker a bit.

protected Point StartPosition { get; set; }

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    StartPosition  = this.Location;
}

protected override void OnMove(EventArgs e)
{
    if (StartPosition == new Point())
        return;

    var currentLocation = Location;

    Location = new Point(StartPosition.X, currentLocation.Y);

    base.OnMove(e);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜