2

I have created a winform application for school project. But in certain situation I want to let user to move the form only vertically by dragging the form.

So, I have tried this.

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

But it doesn't seem to work. It moves the form across the screen. So, is there a way to restrict form movement to vertical?

haZya
  • 285
  • 4
  • 14

2 Answers2

4

You should not set this.Location, but only the this.Location.Y value:

this.Location = pointToMoveTo;

should become

this.Top = pointToMoveTo.Y;

Your original code changed both the X and Y coordinates, effectively doing a diagonal move.

Jens Meinecke
  • 2,904
  • 17
  • 20
  • 1
    Location is a struct, not class, so changing the Y property will not change the location. More info: http://stackoverflow.com/questions/3729873/problem-with-struct-and-property-in-c-sharp – romanoza Jan 29 '16 at 17:17
  • @romanoza You are correct indeed - silly mistake on my part - should update the `Top` property instead. Solution edited. – Jens Meinecke Jan 30 '16 at 05:31
2

Try something like this:

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);
        }
    }
}
romanoza
  • 4,775
  • 3
  • 27
  • 44