Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set autoscroll position on mouse move

Tags:

c#

winforms

I need to update scroll bar position when I click on image and move picturebox. It is always at the beggining, it only moving on the right side (horizontall) and down (vertical).

    private void pictureBox1_MouseMove_1(object sender, MouseEventArgs e)
    {

            ....

            Point currentMousePos = e.Location;
            int distanceX = currentMousePos.X - mouseX;
            int distanceY = currentMousePos.Y - mouseY;
            int newX = pictureBox1.Location.X + distanceX;
            int newY = pictureBox1.Location.Y + distanceY;

            if (newX + pictureBox1.Image.Width + 10 < pictureBox1.Image.Width && pictureBox1.Image.Width + newX + 10 > panel1.Width)
            {
                pictureBox1.Location = new Point(newX, pictureBox1.Location.Y);
            }
            if (newY + pictureBox1.Image.Height + 10 < pictureBox1.Image.Height && pictureBox1.Image.Height + newY + 10 > panel1.Height)
            {
                pictureBox1.Location = new Point(pictureBox1.Location.X, newY);
            }
    }
like image 558
gormit Avatar asked Dec 05 '22 18:12

gormit


1 Answers

I think you need to change the AutoScrollPosition of the parent panel and not play around with the Location points of the PictureBox. After all, the scroll bars of the parent panel are already taking care of the position of the PictureBox.

Try something like this (by the way, my code only does this when a button is pressed, otherwise, I think it would be a weird user interface design):

private Point _StartPoint;

void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left)
    _StartPoint = e.Location;
}

void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    Point changePoint = new Point(e.Location.X - _StartPoint.X, 
                                  e.Location.Y - _StartPoint.Y);
    panel1.AutoScrollPosition = new Point(-panel1.AutoScrollPosition.X - changePoint.X,
                                          -panel1.AutoScrollPosition.Y - changePoint.Y);
  }
}
like image 152
LarsTech Avatar answered Dec 24 '22 13:12

LarsTech