using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; public class MainForm : Form { private PictureBox happyBox = new PictureBox(); private int oldX, oldY; private bool isDragging; private Rectangle dropRect = new Rectangle(100, 100, 140, 170); public MainForm() { happyBox.SizeMode = PictureBoxSizeMode.StretchImage; happyBox.Location = new System.Drawing.Point(64, 32); happyBox.Size = new System.Drawing.Size(50, 50); happyBox.Cursor = Cursors.Hand; happyBox.Image = new Bitmap("happyDude.bmp"); happyBox.MouseDown += new MouseEventHandler(happyBox_MouseDown); happyBox.MouseUp += new MouseEventHandler(happyBox_MouseUp); happyBox.MouseMove += new MouseEventHandler(happyBox_MouseMove); Controls.Add(happyBox); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 361); this.Text = "Dragging Images"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); } void happyBox_MouseMove(object sender, MouseEventArgs e) { if (isDragging) { happyBox.Top = happyBox.Top + (e.Y - oldY); happyBox.Left = happyBox.Left + (e.X - oldX); } } void happyBox_MouseUp(object sender, MouseEventArgs e) { isDragging = false; if (dropRect.Contains(happyBox.Bounds)) MessageBox.Show("You win!", "What an amazing test of skill..."); } void happyBox_MouseDown(object sender, MouseEventArgs e) { isDragging = true; oldX = e.X; oldY = e.Y; } private void MainForm_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.BlueViolet, dropRect); g.DrawString("Drag the happy guy in here...",new Font("Times New Roman", 25), Brushes.WhiteSmoke, dropRect); } [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } }