π Lecture 22 β Attached Events, Keyboard, Mouse, Stylus & Touch Events
π Overview: This lecture continues the discussion of routed events and introduces attached events, which allow windows to handle events from elements that don't define them. It then covers keyboard events, mouse events (including drag-and-drop and mouse capturing), stylus input, and multi-touch events available on Windows 7 or later.
ποΈ Topics Covered
The lecture reviews code from the previous session, introduces attached events with practical examples, explains generic event handling using delegate contravariance, covers keyboard events and keyboard focus, details mouse events including mouse capture and drag-and-drop, discusses stylus input, and introduces basic and manipulation touch events for multi-touch hardware.
π Lecture Summary
Review of Previous Code
The lecture begins with a code example demonstrating how to handle the MouseRightButtonDown event. The handler displays event information from MouseButtonEventArgs, including the Source and OriginalSource types, and toggles a border thickness on the source control. The code shows that listbox items never receive events when clicked, and setting border on a Button has no effect since it has no border element. Handling a halted event can only be done from procedural code.
Attached Events
Attached events are events that can bubble and tunnel through elements that have not defined the event themselves, similar to property value inheritance and attached properties. The lecture presents an example where a Window handles ListBox.SelectionChanged and Button.Click events, even though the Window does not define these events. The XAML markup attributes listbox.selectionchanged and Button.Click are valid because the compiler sees these events defined in the ListBox and Button at runtime, and AddHandler is called directly.
The equivalent procedural code is:
this.AddHandler(ListBox.SelectionChangedEvent,
new SelectionChangedEventHandler(listbox_selectionchanged));
this.AddHandler(Button.ClickEvent, new RoutedEventHandler(Button_Click));
π Definition β Attached Events: Events that can be handled by parent elements that do not define the event themselves, using AddHandler to connect to the event.
π Example: A Window handles both ListBox.SelectionChanged and Button.Click events through XAML attributes, where the event names are prefixed with the type that defines them (e.g., listbox.selectionchanged).
Generic Event Handling with Delegate Contravariance
Theoretically, one handler can handle all events using delegate contravariance, where arguments can be of a base type than the delegate. A single genericHandler method can check the e.RoutedEvent property to determine which event occurred and cast the event arguments accordingly.
void genericHandler(object sender, RoutedEventArgs e)
{
if (e.RoutedEvent == Button.ClickEvent)
{
MessageBox.Show("You just clicked " + e.Source);
}
else if (e.RoutedEvent == ListBox.SelectionChangedEvent)
{
SelectionChangedEventArgs sce = (SelectionChangedEventArgs)e;
if (sce.AddedItems.Count > 0)
MessageBox.Show("You just selected " + sce.AddedItems[0]);
}
}
π Definition β Delegate Contravariance: The ability for an event handler to accept arguments of a base type (e.g., RoutedEventArgs) rather than the specific derived type (e.g., SelectionChangedEventArgs).
Keyboard Events
Keyboard events include KeyDown, KeyUp, and their Preview versions. KeyEventArgs contains properties such as Key, ImeProcessedKey, DeadCharProcessedKey, SystemKey, IsUp, IsDown, IsToggled, KeyStates, IsRepeat, and KeyboardDevice. The static class System.Windows.Input.Keyboard and its PrimaryDevice property are accessible everywhere.
The lecture provides examples for detecting Alt+A key combinations:
Using bitwise AND to check modifiers:
if ((e.KeyboardDevice.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt &&
(e.Key == Key.A || e.SystemKey == Key.A))
{
// Alt+A has been pressed, potentially also with Ctrl, Shift, and/or Windows
}
Using equality check for exact modifier:
if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt &&
(e.Key == Key.A || e.SystemKey == Key.A))
{
// Alt+A and only Alt+A has been pressed
}
You can use KeyboardDevice.IsKeyDown to check if specific keys like left or right Alt are pressed.
Keyboard Focus
Keyboard focus determines which UI element receives keyboard input. The UIElement.Focusable property (true by default), along with events like FocusableChanged, and read-only properties IsKeyboardFocused and IsKeyboardFocusWithin, control focus behavior. To set focus, use Focus or MoveFocus. Related events include IsKeyboardFocusedChanged, IsKeyboardFocusWithinChanged, GotKeyboardFocus, LostKeyboardFocus, PreviewGotKeyboardFocus, and PreviewLostKeyboardFocus.
π Definition β Keyboard Focus: The element that currently receives keyboard input, determined by the Focusable property and focus management methods.
π‘ Why this matters: Understanding keyboard focus is essential for accessibility and proper keyboard navigation in applications.
Mouse Events
Mouse events include:
- MouseEnter and MouseLeave (for rollover effects, though triggers with
IsMouseOverare preferred) - MouseMove and PreviewMouseMove
- MouseLeftButtonDown, MouseRightButtonDown, MouseLeftButtonUp, MouseRightButtonUp, plus the generic MouseDown and MouseUp
- All six events have Preview versions
- MouseWheel and PreviewMouseWheel
Key behaviors:
- If
Visibility=Collapsed, no mouse events are generated - If
Opacity=0, all events are still generated - Null background/brush produces areas with no events, while Transparent does generate events (they look the same but behave differently for hit testing)
MouseEventArgs has five properties of type MouseButtonState (Pressed or Released): LeftButton, RightButton, MiddleButton, XButton1, and XButton2. The GetPosition function returns a Point with X and Y properties β pass null for screen-relative position or an element for position relative to that element.
MouseWheelEventArgs (derived from MouseEventArgs) adds a Delta property. The 12 mouse up/down events get MouseButtonEventArgs, which adds ChangedButton, ButtonState (for the changed button), and ClickCount properties. The Button base class raises a MouseDoubleClick event by checking ClickCount in MouseLeftButtonDown.
π Formula: e.GetPosition(null) β returns mouse position relative to the screen. e.GetPosition(element) β returns mouse position relative to that element.
Drag and Drop
Drag and drop events include DragEnter, DragOver, DragLeave, with Preview versions, Drop and PreviewDrop, QueryContinueDrag and PreviewQueryContinueDrag. Drag and drop works with clipboard content, not elements themselves. It is enabled by setting AllowDrop=true.
These events provide DragEventArgs with methods like GetPosition, and properties Data, Effects, and AllowedEffects (Copy, Move, Link, Scroll, All, None), and KeyStates (LeftMouseButton, RightMouseButton, MiddleMouseButton, ShiftKey, ControlKey, AltKey, or None). Continue events are raised when keyboard or mouse state changes during the operation, and QueryContinueDragEventArgs has KeyStates, EscapePressed, and Action (Continue, Drop, Cancel).
Mouse Capturing
Mouse capturing is important for drag-and-drop operations. When a UI element captures the mouse, it continues receiving mouse events even if the mouse moves outside the element or under another element. Properties include IsMouseCaptured and IsMouseCaptureWithin, and events include GotMouseCapture, LostMouseCapture, IsMouseCaptureChanged, and IsMouseCaptureWithinChanged. Inside MouseMove, you can use a layout or RenderTransform to move the element.
π Definition β Mouse Capture: A state where a UI element receives all mouse events even when the mouse pointer is outside the element's bounds.
Stylus Events
The Stylus can behave like a mouse but has higher resolution, can be inverted, detects whether it's in air or not, and provides pressure sensitivity.
Multi-Touch Events
Multi-touch events are available on Windows 7 or later with multi-touch hardware. Two categories exist:
Basic Touch Events: TouchEnter and TouchLeave, TouchMove and PreviewTouchMove, TouchDown, TouchUp, PreviewTouchDown and PreviewTouchUp, GotTouchCapture and LostTouchCapture. With multiple fingers, events are raised for each finger separately. For the first finger, mouse events are also generated. TouchEventArgs has GetTouchPoint, GetIntermediateTouchPoints, TouchDevice. TouchPoint has Position, Size, Bounds, TouchDevice, Action (Down, Up, Move). Each finger has its own TouchDevice identified by an Id property. Some notebooks support only two simultaneous touch points. A lower-level FrameReported event (which is not even routed) is also raised.
Manipulation Events: Used for panning, rotating, and zooming. These are easy to apply with a Transform. While swiping is easy with basic events, rotation and other gestures are difficult with previous events and lack consistency in behavior between applications. Therefore, using manipulation events is preferred.
β Key Takeaways
Attached events allow a window or parent element to handle events from child elements that define those events, using AddHandler or XAML attributes with type-prefixed event names. Delegate contravariance enables a single generic event handler to process multiple event types by checking the RoutedEvent property. Keyboard events include KeyDown and KeyUp, while mouse events include a comprehensive set of down, up, move, enter, leave, and wheel events β with important differences between null and transparent backgrounds for hit testing. Mouse capturing is essential for drag-and-drop operations to ensure continuous event delivery. Finally, multi-touch events provide both basic touch handling and higher-level manipulation events for panning, rotating, and zooming, with the latter being preferred for consistency across applications.
π§ Quick Revision Questions
- What is an attached event, and how does a window handle an event like
ListBox.SelectionChangedthat it doesn't define? - How can a single event handler process both
Button.ClickandListBox.SelectionChangedevents? What is delegate contravariance? - What is the difference between checking keyboard modifiers with
&(bitwise AND) versus==(equality)? - Why does a
nullbackground behave differently from aTransparentbackground for mouse hit testing? - What makes manipulation events (for panning, rotating, zooming) preferred over basic touch events for complex gestures?