Moving pictureBox in panel
I have a project in C#, WindowsForms and I created a panel
that contains a pictureBox
that is much bigger than his parent.
I turned panel.AutoScroll
to true
and what I want to do is dr开发者_运维百科agging this pictureBox
in panel
instead of catching a scroll and moving it.
I.e. when I grab an image and move cursor to left and down I would like to get the same behavior as I will do it with panel
's scrolls.
How to do it ?
Ok, I got it. ;-) If anyone else has the same problem, here is solution:
protected Point clickPosition;
protected Point scrollPosition;
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
this.clickPosition.X = e.X;
this.clickPosition.Y = e.Y;
}
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
scrollPosition.X = scrollPosition.X + clickPosition.X - e.X;
scrollPosition.Y = scrollPosition.Y + clickPosition.Y - e.Y;
this.panel.AutoScrollPosition = scrollPosition;
}
}
a smaller variant of the hsz solution :)
protected Point clickPosition;
protected Point scrollPosition;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
this.clickPosition = e.Location;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.SuspendLayout();
this.scrollPosition += (Size)clickPosition - (Size)e.Location;
this.panel1.AutoScrollPosition = scrollPosition;
this.ResumeLayout(false);
}
}
an improved solution from hsz', with limitation of scroll, but I allow only vertical scroll
protected Point clickPosition;
protected Point scrollPosition;
private void picBoxScan_MouseDown(object sender, MouseEventArgs e)
{
this.clickPosition.X = e.X;
this.clickPosition.Y = e.Y;
}
private void picBoxScan_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
scrollPosition.X = panelViewFile.AutoScrollPosition.X;
scrollPosition.Y = scrollPosition.Y + (clickPosition.Y - e.Y);
scrollPosition.Y = Math.Min(scrollPosition.Y,panelViewFile.VerticalScroll.Maximum);
scrollPosition.Y = Math.Max(scrollPosition.Y,panelViewFile.VerticalScroll.Minimum);
panelViewFile.AutoScrollPosition = scrollPosition;
}
}
精彩评论