Mouse click and drag Event WPF
Asked Answered
F

3

16

I am developing an analog clock picker control. The user is able to click on the minute or hour hand and drag to turn the needle to select the specific time. I was wondering how to detect such a click and drag event.

I tried using MouseLeftButtonDown + MouseMove but I cannot get it to work as MouseMove is always trigger when the mousemove happen despite me using a flag. Is there any easier way?

public bool dragAction = false;

private void minuteHand_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    dragAction = true;
    minuteHand_MouseMove(this.minuteHand, e);
}

private void minuteHand_MouseMove(object sender, MouseEventArgs e)
{
    if (dragAction == true)
    {
       //my code: moving the needle
    }
 }

 private void minuteHand_MouseLeftButtonUp(object sender, MouseEventArgs e)
 {
    dragAction = false;
 }
Flocculant answered 3/7, 2013 at 7:2 Comment(0)
B
9

I think this is the easiest and most straightforward way :

 private void Window_MouseMove(object sender, MouseEventArgs e) {
     if (e.LeftButton == MouseButtonState.Pressed) {
        this.DragMove();
     }
 }
Bartholomew answered 10/6, 2015 at 4:36 Comment(0)
S
5
public bool dragAction = false;

private void minuteHand_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    dragAction = true;
    minuteHand_MouseMove(this.minuteHand, e);
}

private void minuteHand_MouseMove(object sender, MouseEventArgs e)
{
    if (dragAction == true)
    {
       this.DragMove();
    }
 }

 private void minuteHand_MouseLeftButtonUp(object sender, MouseEventArgs e)
 {
    dragAction = false;
 }

does the trick

Sisal answered 5/12, 2013 at 13:58 Comment(2)
Isn't this just the same as the original post?Clammy
Original was missing: this.DragMove() functionSisal
P
4

You can make things easier and need not handle mouse down / up :

private void minuteHand_MouseMove(object sender, MouseEventArgs e)
{
    if (Mouse.LeftButton == MouseButtonState.Pressed)
    {
        //my code: moving the needle
    }
 }    
Primordium answered 3/7, 2013 at 8:15 Comment(2)
I want the user to click and drag rather than just moving the mouse.Flocculant
In wpf drag&Drop, use always PreviewMouseDown. That way you will achieve it working it with MouseMove. (MousDown is bubbling and not suitable for drag&drop)Primordium

© 2022 - 2024 — McMap. All rights reserved.