#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 software development and sailing.

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 comment