#684 – Mouse Events Occur for the Element That the Mouse Is Over

Mouse events normally fire for the element that mouse is current positioned over.  In the example below, notice that the Source property for the event handler always refers to the Label that the mouse is currently positioned over.

    <StackPanel MouseDown="Label_MouseDown" MouseUp="Label_MouseUp" MouseMove="Label_MouseMove">
        <Label Content="Sistine" Background="ForestGreen" Padding="10,20"/>
        <Label Content="Buonarroti" Background="Peru" Padding="10,20"/>
    </StackPanel>

 

        private void Label_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label l = e.Source as Label;
            if (l != null)
                Console.WriteLine(string.Format("MouseDown on {0}", l.Content));
        }

        private void Label_MouseUp(object sender, MouseButtonEventArgs e)
        {
            Label l = e.Source as Label;
            if (l != null)
                Console.WriteLine(string.Format("MouseUp on {0}", l.Content));
        }

        private void Label_MouseMove(object sender, MouseEventArgs e)
        {
            Label l = e.Source as Label;
            if (l != null)
            {
                Point p = e.GetPosition(null);
                Console.WriteLine(string.Format("MouseMove on {0} at ({1},{2})", l.Content, p.X, p.Y));
            }
        }

If we press the mouse button while over one Label, move to the other Label and release the button, we get:

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #684 – Mouse Events Occur for the Element That the Mouse Is Over

  1. Pingback: Dew Drop – November 6, 2012 (#1,437) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: