-
Notifications
You must be signed in to change notification settings - Fork 152
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
1
commit 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.
Open
Changes from all commits
Commits
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
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,150 @@ | |
| 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) | ||
| { | ||
| keyRoutedEventArgs.Handled = true; | ||
| Interaction.ExecuteActions(sender, Actions, keyRoutedEventArgs); | ||
| return; | ||
| } | ||
|
|
||
| if (!CheckModifiers()) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| keyRoutedEventArgs.Handled = true; | ||
| Interaction.ExecuteActions(sender, Actions, keyRoutedEventArgs); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Checks whether all required modifier keys specified in <see cref="Modifiers"/> | ||
| /// are currently pressed. | ||
| /// </summary> | ||
| /// <returns><see langword="true"/> if the modifier state matches; otherwise, <see langword="false"/>.</returns> | ||
|
|
||
| private bool CheckModifiers() => | ||
| Match(VirtualKeyModifiers.Control, VirtualKey.Control) && | ||
| Match(VirtualKeyModifiers.Shift, VirtualKey.Shift) && | ||
| Match(VirtualKeyModifiers.Menu, VirtualKey.Menu); | ||
|
|
||
| /// <summary> | ||
| /// Determines whether a specific modifier key is required and whether it is currently pressed. | ||
| /// </summary> | ||
| /// <param name="mod">The modifier flag to test.</param> | ||
| /// <param name="key">The physical key corresponding to the modifier.</param> | ||
| /// <returns><see langword="true"/> if the modifier requirement matches the current key state; otherwise, <see langword="false"/>.</returns> | ||
| private bool Match(VirtualKeyModifiers mod, VirtualKey key) | ||
| { | ||
| bool required = (Modifiers & mod) != 0; | ||
| bool pressed = IsDown(key); | ||
| return required == pressed; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Checks whether the specified key is currently in the <see cref="CoreVirtualKeyStates.Down"/> state. | ||
| /// </summary> | ||
| /// <param name="key">The key to test.</param> | ||
| /// <returns><see langword="true"/> if the key is pressed; otherwise, <see langword="false"/>.</returns> | ||
| private static bool IsDown(VirtualKey key) | ||
| { | ||
| var state = InputKeyboardSource.GetKeyStateForCurrentThread(key); | ||
|
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. Let's change this so it's called once in |
||
| return state.HasFlag(CoreVirtualKeyStates.Down); | ||
| } | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Small formatting thing. Let's add a space here. Also, personally I would put all the
DependencyPropertydeclarations together and all the property declarations below, but we don't currently have a uniform convention on this, and this PR has actually sparked a debate on this in the Discord.