仅垂直移动表单

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

您必须拦截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); } } 

这样做(但它不漂亮):

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

您可以通过将表单的位置重置为初始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); }