Introduction
This tip discusses how to exchange the images of two PictureBox
es by dragging one on the other.
Using the Code
Open Visual Studio 2008 Windows Form with two PictureBox
es created.
Image^ im;
Point PicLoc;
int ox,oy;
bool md;
private: System::Void pictureBox1_MouseDown
(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
PicLoc=this->pictureBox1->Location;
im=pictureBox2->Image;
this->pictureBox1->BringToFront();
ox=e->X;
oy=e->Y;
md=true;
}
private: System::Void pictureBox1_MouseUp
(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
md=false;
int p1=e->X+pictureBox1->Location.X;
int p2=e->Y+pictureBox1->Location.Y;
if(pictureBox2->Location.X<p1 &&
p1<pictureBox2->Location.X+pictureBox2->Size.Width){
if(pictureBox2->Location.Y<p2 &&
p2<pictureBox2->Location.Y+pictureBox2->Size.Height){
this->pictureBox2->Image=this->pictureBox1->Image;
this->pictureBox1->Image=im;
}
}
this->pictureBox1->Location=PicLoc;
}
private: System::Void pictureBox1_MouseMove
(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
if(md){
this->pictureBox1->Left +=e->X-ox;
this->pictureBox1->Top +=e->Y-oy;
}
}
Effect
Drag PictureBox1
on to PictureBox2
:
The images have been exchanged. PictureBox1
goes back to the initial position when mouse is up.
History