1

I would like to allow user to drag the button to a point either right(+X) or left(-X) based on which direction the user drags the button. I'm new to windows forms and a walk-through would be appreciated.(In my example, I hard-coded the new position increment by 10 pixels but I want the user to be able to drag the button as far as he wants). Here's my current code:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        Load +=Form1_Load;

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    bool isDragged = false;


    private void button1_MouseDown(object sender, MouseEventArgs e)
    {

        if (e.Button == MouseButtons.Left)
        {
            isDragged = true;
        }
        else
        {
            isDragged = false;
        }
    }

    private void button1_MouseMove(object sender, MouseEventArgs e)
    {

        if (isDragged)
        {
            button1.Location = new Point(button1.Location.X + 10, button1.Location.Y); 
        }

        isDragged = false;
    }
}   
MirrorEyes
  • 57
  • 4
  • You can try the solution here http://stackoverflow.com/questions/2063974/how-do-i-capture-the-mouse-move-event-in-my-winform-application – Nathan Nov 07 '14 at 02:35

1 Answers1

0

Try this:

private Point mouseDown, buttonLocation;
private bool isDragged = false;

private void button1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        isDragged = true;

        mouseDown = Cursor.Position;
        buttonLocation = button1.Location;
    }

}

private void button1_MouseMove(object sender, MouseEventArgs e)
{
    if (isDragged)
    {
        button1.Location = new Point(buttonLocation.X + (Cursor.Position.X - mouseDown.X), button1.Location.Y);
    }
}

private void button1_MouseUp(object sender, MouseEventArgs e)
{
    isDragged = false;
}