diff --git a/Terminal.Gui/Views/Shortcut.cs b/Terminal.Gui/Views/Shortcut.cs index a260dc7f9..a0df78b86 100644 --- a/Terminal.Gui/Views/Shortcut.cs +++ b/Terminal.Gui/Views/Shortcut.cs @@ -454,7 +454,7 @@ public class Shortcut : View, IOrientation, IDesignable SetHelpViewDefaultLayout (); SetKeyViewDefaultLayout (); ShowHide (); - UpdateKeyBinding (); + UpdateKeyBinding (Key.Empty); } } @@ -546,9 +546,10 @@ public class Shortcut : View, IOrientation, IDesignable throw new ArgumentNullException (); } + Key oldKey = _key; _key = value; - UpdateKeyBinding (); + UpdateKeyBinding (oldKey); KeyView.Text = Key == Key.Empty ? string.Empty : $"{Key}"; ShowHide (); @@ -567,7 +568,7 @@ public class Shortcut : View, IOrientation, IDesignable { _keyBindingScope = value; - UpdateKeyBinding (); + UpdateKeyBinding (Key.Empty); } } @@ -619,7 +620,7 @@ public class Shortcut : View, IOrientation, IDesignable KeyView.KeyBindings.Clear (); } - private void UpdateKeyBinding () + private void UpdateKeyBinding (Key oldKey) { if (Key != null) { @@ -629,11 +630,20 @@ public class Shortcut : View, IOrientation, IDesignable if (KeyBindingScope.FastHasFlags (KeyBindingScope.Application)) { + if (oldKey != Key.Empty) + { + Application.KeyBindings.Remove (oldKey); + } + Application.KeyBindings.Remove (Key); Application.KeyBindings.Add (Key, this, Command.Accept); } else { + if (oldKey != Key.Empty) + { + KeyBindings.Remove (oldKey); + } KeyBindings.Remove (Key); KeyBindings.Add (Key, KeyBindingScope | KeyBindingScope.HotKey, Command.Accept); } diff --git a/UnitTests/Views/ShortcutTests.cs b/UnitTests/Views/ShortcutTests.cs index f3d54ddbf..133d66874 100644 --- a/UnitTests/Views/ShortcutTests.cs +++ b/UnitTests/Views/ShortcutTests.cs @@ -570,4 +570,26 @@ public class ShortcutTests current.Dispose (); } + + [Fact] + public void Changing_Key_Removes_Previous () + { + var newActionCount = 0; + + Shortcut shortcut = new Shortcut (Key.N.WithCtrl, "New", () => newActionCount++); + Application.Current = new Toplevel (); + Application.Current.Add (shortcut); + + Assert.Equal (0, newActionCount); + Assert.True (Application.OnKeyDown (Key.N.WithCtrl)); + Assert.False (Application.OnKeyDown (Key.W.WithCtrl)); + Assert.Equal (1, newActionCount); + + shortcut.Key = Key.W.WithCtrl; + Assert.False (Application.OnKeyDown (Key.N.WithCtrl)); + Assert.True (Application.OnKeyDown (Key.W.WithCtrl)); + Assert.Equal (2, newActionCount); + + Application.Current.Dispose (); + } }