如何只垂直移动无边框形式?

时间:2016-01-29 10:40:03

标签: c# .net winforms

我为学校项目创建了一个winform应用程序。但在某些情况下,我想让用户只通过拖动表单垂直移动表单。

所以,我试过这个。

 private bool dragging = false;
 private Point pointClicked;

 private void Form1_MouseMove(object sender, MouseEventArgs e)
 {
     if (dragging)
     {
         Point pointMoveTo;
         pointMoveTo = this.PointToScreen(new Point(e.Y,e.Y));
         pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y);
         this.Location = pointMoveTo;
     }
 }

 private void Form1_MouseDown(object sender, MouseEventArgs e)
 {
     dragging = true;
     pointClicked = new Point(e.X, e.Y);
 }
 private void Form1_MouseDown(object sender, MouseEventArgs e)
 {
     dragging = false;
 }

但它似乎不起作用。它将表单移动到屏幕上。那么,有没有办法将表格移动限制为垂直?

2 个答案:

答案 0 :(得分:4)

您不应该设置this.Location,而只能设置this.Location.Y值:

this.Location = pointToMoveTo;

应该成为

this.Top = pointToMoveTo.Y;

你的原始代码改变了X和Y坐标,有效地进行了对角移动。

答案 1 :(得分:2)

尝试这样的事情:

public partial class Form1 : Form
{
    private bool dragging = false;
    private int pointClickedY;

    public Form1() {
        InitializeComponent();
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e) {
        dragging = true;
        pointClickedY = e.Y;
    }

    private void Form1_MouseUp(object sender, MouseEventArgs e) {
        dragging = false;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e) {
        if (dragging) {
            int pointMoveToY = e.Y;
            int delta = pointMoveToY - pointClickedY;
            Location = new Point(Location.X, Location.Y + delta);
        }
    }
}