Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Image click event

Tags:

mouseevent

wpf

I can find only MouseDown Event and MouseUp Event on a image in WPF. This causes some problem if I do MouseDown on some Image, Move the mouse and MouseUp event happens on some other image. Is there any other event that I can use to solve this problem. like MouseClick Event for Button element.

like image 326
user279244 Avatar asked Dec 08 '22 03:12

user279244


2 Answers

If you really must use an image then there's a couple of things you can do to check for a "click".

  1. Check the time between the two events. If it's less than your threshold, then treat the mouse up as a click. You'll need to store the time of the mouse down event.

  2. Check that the sender of both events is the same. Again you'll need to store the sender of the mouse down event.

You might also want to check that it's the left button that's been pressed and released.

Combining the two:

    private DateTime downTime;
    private object downSender;

    private void Image_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            this.downSender = sender;
            this.downTime = DateTime.Now;
        }
    }

    private void Image_MouseUp(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Released &&
            sender == this.downSender)
        {
            TimeSpan timeSinceDown = DateTime.Now - this.downTime;
            if (timeSinceDown.TotalMilliseconds < 500)
            {
                // Do click
            }
        }
    }

There's actually a third thing you can do: Check the mouse position.

    private Point downPosition;

save the position:

    this.downPosition = e.GetPosition(sender as Image);

then check it in the MouseUp event, again with a tolerance value.

like image 62
ChrisF Avatar answered Dec 09 '22 17:12

ChrisF


Are you sure that you want just an image or do you actually want a button with an image as content? A button with an image will have the click event.

like image 21
Wallstreet Programmer Avatar answered Dec 09 '22 17:12

Wallstreet Programmer