如何在Windows应用商店应用中创建键盘快捷键(如Ctrl + C)

时间:2014-08-24 07:40:32

标签: windows-runtime windows-store-apps

我想在我的应用程序中创建键盘快捷键,例如 Ctrl + C 进行复制。如果TextBox具有焦点,我也想忽略该快捷方式。

1 个答案:

答案 0 :(得分:0)

首先,您需要一种方法来检查是否按下了控制键。 CoreWindow.GetKeyState将完成这项工作,但使用起来可能有点棘手,所以我创建了一个帮助类:

public class ModifierKeys
{
    #region ShiftIsDown property

    public static bool ShiftIsDown 
    { 
        get
        {
            return (Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift) & CoreVirtualKeyStates.Down) != 0;
        }
    }

    public static bool OnlyShiftIsDown 
    { 
        get
        {
            return ShiftIsDown && !AltIsDown && !ControlIsDown;
        }
    }

    #endregion

    #region AltIsDown property

    public static bool AltIsDown
    {
        get
        {
            return (Window.Current.CoreWindow.GetKeyState(VirtualKey.Menu) & CoreVirtualKeyStates.Down) != 0;
        }
    }

    public static bool OnlyAltIsDown
    {
        get
        {
            return !ShiftIsDown && AltIsDown && !ControlIsDown;
        }
    }

    #endregion

    #region ControlIsDown property

    public static bool ControlIsDown
    {
        get
        {
            return (Window.Current.CoreWindow.GetKeyState(VirtualKey.Control) & CoreVirtualKeyStates.Down) != 0;
        }

    }

    public static bool OnlyControlIsDown
    {
        get
        {
            return !ShiftIsDown && !AltIsDown && ControlIsDown;
        }
    }

    #endregion

    #region NoModifierKeyIsDown property

    public static bool NoModifierKeyIsDown
    {
        get
        {
            return !ShiftIsDown && !AltIsDown && !ControlIsDown;
        }
    }

    #endregion
}

现在在页面OnNavigateTo/From中订阅/取消订阅关键事件:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        /*...*/
        Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
    }

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        /*...*/
        Window.Current.CoreWindow.KeyDown -= CoreWindow_KeyDown;
    }

CoreWindow_KeyDown看起来像这样:

void CoreWindow_KeyDown(CoreWindow sender, KeyEventArgs args)
{
    var focusedElement = FocusManager.GetFocusedElement();

    if (args.KeyStatus.WasKeyDown == false && ModifierKeys.OnlyControlIsDown &&
        !(focusedElement is TextBox)
        )
    {
            if (args.VirtualKey == VirtualKey.X)
            {
                /*...cut...*/
            }
            else if (args.VirtualKey == VirtualKey.V)
            {
                /*...paste...*/
            }
            else if (args.VirtualKey == VirtualKey.C)
            {
                /*...copy...*/
            }
    }
}