-
Notifications
You must be signed in to change notification settings - Fork 153
Extend KeyDownTriggerBehavior with Modifiers and ability to handle already handled events #853
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Irina-Konovalova
wants to merge
5
commits into
CommunityToolkit:main
Choose a base branch
from
Ecierge:key-down-trigger-behavior-improvements
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+139
−16
Open
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
8b01b15
Improve KeyDownTriggerBehavior to support PreviewKeyDown, handled eve…
1163694
Refactor modifier key handling in KeyDownTriggerBehavior
4be6b21
Add CheckModifierKeys property and preserve original behavior
89a88e2
Update components/Behaviors/src/Keyboard/KeyDownTriggerBehavior.cs
Irina-Konovalova 5ad24e6
Remove duplicate using directive
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,53 +8,146 @@ | |
| namespace CommunityToolkit.WinUI.Behaviors; | ||
|
|
||
| /// <summary> | ||
| /// This behavior listens to a key down event on the associated <see cref="UIElement"/> when it is loaded and executes an action. | ||
| /// A behavior that listens to <see cref="UIElement.PreviewKeyDown"/> on the associated | ||
| /// <see cref="FrameworkElement"/> and executes its actions when the specified key and | ||
| /// optional modifier keys are pressed. Supports capturing handled events. | ||
| /// </summary> | ||
| [TypeConstraint(typeof(FrameworkElement))] | ||
| public class KeyDownTriggerBehavior : Trigger<FrameworkElement> | ||
| { | ||
| private KeyEventHandler? _handler; | ||
|
|
||
| /// <summary> | ||
| /// Identifies the <see cref="Key"/> property. | ||
| /// Identifies the <see cref="Key"/> dependency property. | ||
| /// </summary> | ||
| public static readonly DependencyProperty KeyProperty = DependencyProperty.Register( | ||
| nameof(Key), | ||
| typeof(VirtualKey), | ||
| typeof(KeyDownTriggerBehavior), | ||
| new PropertyMetadata(null)); | ||
| public static readonly DependencyProperty KeyProperty = | ||
| DependencyProperty.Register( | ||
| nameof(Key), | ||
| typeof(VirtualKey), | ||
| typeof(KeyDownTriggerBehavior), | ||
| new PropertyMetadata(VirtualKey.None)); | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the key to listen when the associated object is loaded. | ||
| /// Gets or sets the key that triggers the behavior. | ||
| /// </summary> | ||
| public VirtualKey Key | ||
| { | ||
| get => (VirtualKey)GetValue(KeyProperty); | ||
| set => SetValue(KeyProperty, value); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Identifies the <see cref="Modifiers"/> dependency property. | ||
| /// </summary> | ||
| public static readonly DependencyProperty ModifiersProperty = | ||
| DependencyProperty.Register( | ||
| nameof(Modifiers), | ||
| typeof(VirtualKeyModifiers), | ||
| typeof(KeyDownTriggerBehavior), | ||
| new PropertyMetadata(VirtualKeyModifiers.None)); | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the modifier keys that must be pressed together with <see cref="Key"/>. | ||
| /// </summary> | ||
| public VirtualKeyModifiers Modifiers | ||
| { | ||
| get => (VirtualKeyModifiers)GetValue(ModifiersProperty); | ||
| set => SetValue(ModifiersProperty, value); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Identifies the <see cref="HandledEventsToo"/> dependency property. | ||
| /// </summary> | ||
| public static readonly DependencyProperty HandledEventsTooProperty = | ||
| DependencyProperty.Register( | ||
| nameof(HandledEventsToo), | ||
| typeof(bool), | ||
| typeof(KeyDownTriggerBehavior), | ||
| new PropertyMetadata(true)); | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets a value indicating whether the behavior should receive | ||
| /// <see cref="UIElement.PreviewKeyDown"/> events even if they were already handled. | ||
| /// </summary> | ||
| public bool HandledEventsToo | ||
| { | ||
| get => (bool)GetValue(HandledEventsTooProperty); | ||
| set => SetValue(HandledEventsTooProperty, value); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| protected override void OnAttached() | ||
| { | ||
| AssociatedObject.KeyDown += OnAssociatedObjectKeyDown; | ||
| _handler = OnPreviewKeyDown; | ||
|
|
||
| AssociatedObject.AddHandler( | ||
| UIElement.PreviewKeyDownEvent, | ||
| _handler, | ||
| HandledEventsToo); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| protected override void OnDetaching() | ||
| { | ||
| AssociatedObject.KeyDown -= OnAssociatedObjectKeyDown; | ||
| if (_handler is not null) | ||
| { | ||
| AssociatedObject.RemoveHandler( | ||
| UIElement.PreviewKeyDownEvent, | ||
| _handler); | ||
|
|
||
| _handler = null; | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Invokes the current actions when the <see cref="Key"/> is pressed. | ||
| /// Handles the <see cref="UIElement.PreviewKeyDown"/> event and executes the associated actions | ||
| /// when the specified <see cref="Key"/> and <see cref="Modifiers"/> match. | ||
| /// </summary> | ||
| /// <param name="sender">The source <see cref="UIElement"/> instance.</param> | ||
| /// <param name="keyRoutedEventArgs">The arguments for the event (unused).</param> | ||
| private void OnAssociatedObjectKeyDown(object sender, KeyRoutedEventArgs keyRoutedEventArgs) | ||
| private void OnPreviewKeyDown(object sender, KeyRoutedEventArgs keyRoutedEventArgs) | ||
| { | ||
| if (keyRoutedEventArgs.Key == Key) | ||
| if (keyRoutedEventArgs.Key != Key) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (!CheckModifiers()) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Upon further consideration, this is actually a breaking change. In order to retain the existing behavior, we need to introduce a new property that declares whether or not to check for modifiers. Its default value needs to be false. |
||
| { | ||
| keyRoutedEventArgs.Handled = true; | ||
| Interaction.ExecuteActions(sender, Actions, keyRoutedEventArgs); | ||
| return; | ||
| } | ||
|
|
||
| keyRoutedEventArgs.Handled = true; | ||
| Interaction.ExecuteActions(sender, Actions, keyRoutedEventArgs); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Checks whether all required modifier keys specified in <see cref="Modifiers"/> | ||
| /// are currently pressed. Retrieves the physical key states once and evaluates | ||
| /// them against the required modifier flags. | ||
| /// </summary> | ||
| /// <returns><see langword="true"/> if the current modifier state matches the requirements; otherwise, <see langword="false"/>.</returns> | ||
| private bool CheckModifiers() | ||
| { | ||
| bool ctrl = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down); | ||
| bool shift = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down); | ||
| bool alt = InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down); | ||
|
|
||
| return Match(VirtualKeyModifiers.Control, ctrl) | ||
| && Match(VirtualKeyModifiers.Shift, shift) | ||
| && Match(VirtualKeyModifiers.Menu, alt); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Compares whether a specific modifier flag is required and whether the | ||
| /// corresponding key is currently pressed. | ||
| /// </summary> | ||
| /// <param name="mod">The modifier flag to evaluate.</param> | ||
| /// <param name="isDown">The current physical key state for that modifier.</param> | ||
| /// <returns><see langword="true"/> if the requirement matches the key state; otherwise, <see langword="false"/>.</returns> | ||
| private bool Match(VirtualKeyModifiers mod, bool isDown) | ||
| { | ||
| bool required = (Modifiers & mod) != 0; | ||
| return required == isDown; | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.