Mouse moving a picture box in C++ GUI
May 29, 2020 at 5:36am UTC
I am trying to move a picture box and drag it to a different location on the form using the left button pushed down on the mouse. The code below moves the picture box, but the box isn't in sync with the mouse cursor. I appreciate any help with this issue. Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
private : System::Void pictureBox1_MouseMove(System::Object^ sender,
System::Windows::Forms::MouseEventArgs^ e) {
Point p;
p.X = e->X;
p.Y = e->Y;
if (e->Button == System::Windows::Forms::MouseButtons::Left)
{
Point p = Cursor->Position;
pictureBox1->Location = p;
textBox1->Text = Cursor->Position.ToString();
textBox2->Text = e->Location.ToString();
}
}
Last edited on May 29, 2020 at 5:37am UTC
May 29, 2020 at 7:06am UTC
but the box isn't in sync with the mouse cursor.
What exactly do you mean ?
Common practice is to store the variables in the form class
1 2
bool dragging = false ;
int currentX, currentY;
In the mouse down event
1 2 3
dragging = true ;
currentX = e->X;
currentY = e->Y;
In the mouse up event:
dragging = false ;
In the mouse move event:
1 2 3 4 5 6 7
if (dragging)
{
pictureBox1->Top = pictureBox1->Top + (e->Y - currentY);
pictureBox1->Left = pictureBox1->Left + (e->X - currentX);
textBox1->Text = Cursor->Position.ToString();
textBox2->Text = e->Location.ToString();
}
The Cursor->Position gives you the screen coordinates, e->Location the cursor pos inside the picture box
Hope this makes sense.
May 30, 2020 at 3:44am UTC
Thank you so much. it works now.
Topic archived. No new replies allowed.