As stated in other answers, setting IsAltKeyRequiredInAccessKeyDefaultScope
avoids invoking actions for access keys without pressing the Alt key. However, this can also have the effect of disabling the Enter key (for invoking the default action) and Esc key (for invoking the Cancel action).
Using the suggested workaround instead, and testing for Key.Enter
and Key.Escape
, can circumvent this problem. However, you might then find that menu items cannot be selected by their access key without pressing the Alt key, which could be a problem if a button in scope uses the same access key.
An alternative could then be to handle the access key event by checking whether a potentially invokable AccessText
control is within a MenuItem
or not, something along these lines:
EventManager.RegisterClassHandler(
typeof(UIElement),
AccessKeyManager.AccessKeyPressedEvent,
new AccessKeyPressedEventHandler(OnAccessKeyPressed));
...
static void OnAccessKeyPressed(object accessKeyTarget, AccessKeyPressedEventArgs e)
{
if (!e.Handled && e.Scope == null &&
(Keyboard.Modifiers & ModifierKeys.Alt) != ModifierKeys.Alt &&
!ShouldElementHandleAccessKeysWhenAltIsNotPressed(accessKeyTarget as UIElement))
{
e.Target = null;
e.Handled = true;
}
}
static bool ShouldElementHandleAccessKeysWhenAltIsNotPressed(UIElement element)
{
if (element == null) return false;
var accessText = element as AccessText;
if (accessText != null && !IsDecendantOfMenuItem(accessText)) return false;
return true;
}
static bool IsDecendantOfMenuItem(DependencyObject element)
{
for (; element != null; element = VisualTreeHelper.GetParent(element))
if (element is MenuItem) return true;
return false;
}