Click here to Skip to main content
15,888,816 members
Articles / Programming Languages / C++/CLI
Tip/Trick

PictureBox Image Exchange by Drag and Drop (just using mouse event)

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
30 Apr 2012CPOL 11.1K  
Many drag and drop effects can be simply done by mouse event.

Introduction

This tip discusses how to exchange the images of two PictureBoxes by dragging one on the other.

Using the Code

Open Visual Studio 2008 Windows Form with two PictureBoxes created.

???2

C++
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.

???3

History

  • Version 1: 28/4/2012

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --