-
Drag n Drop Button
I'm trying to drag and drop a button around a form, when i release the mouse the button is not where i wish it to be.
Code:
/*
* Created by SharpDevelop.
* User: Bombdrop
* Date: 03/08/2005
* Time: 12:00
*
*/
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Drag
{
/// <summary>
/// Description of MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private Point location = new Point();
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
[STAThread]
public static void Main(string[] args)
{
Application.Run(new MainForm());
}
#region Windows Forms Designer generated code
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent() {
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(56, 192);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(160, 24);
this.button1.TabIndex = 3;
this.button1.Text = "button1";
this.button1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Button1MouseDown);
//
// MainForm
//
this.AllowDrop = true;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.button1);
this.Name = "MainForm";
this.Text = "MainForm";
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.MainFormDragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.MainFormDragEnter);
this.ResumeLayout(false);
}
#endregion
void MainFormDragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
location.X=e.X;
location.Y=e.Y;
button1.Location=location;
}
void MainFormDragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
void Button1MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.button1.DoDragDrop(button1,DragDropEffects.Move);
}
}
}
-
Re: Drag n Drop Button
According to MSDN e.X and e.Y describe the position of the mouse pointer not of the control that is being dragged. This means that you would have to remember the mousepointers offset to the button during the drag by putting it in a global variable (Point).