我为学校项目创建了一个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;
}
但它似乎不起作用。它在屏幕上移动窗体。那么,有没有办法将表单移动限制为垂直?
不应设置
this.Location
,而应仅设置 this.Location.Y
值:
this.Location = pointToMoveTo;
应该成为
this.Top = pointToMoveTo.Y;
您的原始代码更改了 X 和 Y 坐标,有效地执行了对角线移动。
尝试这样的事情:
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);
}
}
}