仅垂直移动表单

时间:2010-11-29 09:36:58

标签: c# .net winforms

如何创建一个仅由TitleBar垂直移动的WinForms表单?

3 个答案:

答案 0 :(得分:5)

您必须拦截Windows发送的WM_MOVING通知消息。这是代码:

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

答案 1 :(得分:3)

这样做(但不是很漂亮):

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

答案 2 :(得分:1)

您可以通过将表单的位置重置为初始X值和移动的Y值来快捷移动操作。这个解决方案很简单,但会闪烁一点。

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