Reputation: 13306
I have a WinForm application, I'm trying to move a pictureBox in a Form using MouseMove Event
, but i can't figure out what's the right calculation should i do on MouseMove, when i first the pictureBox , its location changes in a senseless way then on moving the pictureBox Location moves correctly.
It's a Panel name OuterPanel
which contains the pictureBox picBox
, here the code im using :
private void picBox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point p = OuterPanel.PointToClient(MousePosition);
picBox.Location = this.PointToClient(p);
}
}
P.S : the goal is moving image after zooming in, like windows photo viewer
Update : ConvertFromChildToForm
method
private Point ConvertFromChildToForm(int x, int y,Control control)
{
Point p = new Point(x, y);
control.Location = p;
return p;
}
Upvotes: 0
Views: 11164
Reputation: 14085
Try this. It's beautiful.
const uint WM_NCLBUTTONDOWN = 161;
const uint HTCAPTION = 2;
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr window, uint message, IntPtr wParam, IntPtr lParam);
public Form1()
{
PictureBox picBox = new PictureBox();
picBox.Text = "this control is crazy!";
picBox.BackColor = Color.Red;
picBox.SetBounds(8, 8, 128, 64);
picBox.MouseDown += OnMouseDown;
Controls.Add(picBox);
}
private void OnMouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage((sender as Control).Handle, WM_NCLBUTTONDOWN, (IntPtr) HTCAPION, IntPtr.Zero);
}
The catch is only that you have to work with WinApi. And it won't let labels move. Dunno why.
Upvotes: 0
Reputation: 61
with use
ControlMoverOrResizer
class in this article you can do movable and resizable control in run time just with a line of code! :) example:
ControlMoverOrResizer.Init(button1);
and now button1 is a movable and resizable control!
Upvotes: 0
Reputation: 2163
You have to Manage three Events to get it done correctly :
MouseDown
MouseMove
MouseUp
Here is a Related SO Question..
Your Code for picBox
:
private void picBox_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point p = ConvertFromChildToForm(e.X, e.Y, picBox);
iOldX = p.X;
iOldY = p.Y;
iClickX = e.X;
iClickY = e.Y;
clicked = true;
}
}
private void picBox_MouseMove(object sender, MouseEventArgs e)
{
if (clicked)
{
Point p = new Point(); // New Coordinate
p.X = e.X + picBox.Left;
p.Y = e.Y + picBox.Top;
picBox.Left = p.X - iClickX;
picBox.Top = p.Y - iClickY;
}
}
private void picBox_MouseUp(object sender, MouseEventArgs e)
{
clicked = false;
}
private Point ConvertFromChildToForm(int x, int y, Control control)
{
Point p = new Point(x, y);
control.Location = p;
return p;
}
ConvertFromChildToForm
method from Mur Haf Soz
Upvotes: 4