WPF 纯代码实现自定义快捷键

来源:互联网 发布:西溪悦榕庄 知乎 编辑:程序博客网 时间:2024/05/22 12:30

一个项目要自定义快捷键,找了一下“度娘”,找到的基本都是xmal方式的,与我的需求不太一致(用户自定义快捷键,随意性大,可能是本人能力不足,没有充分了解xmal方式的设置吧  ^_^)。经过一番捣弄,通过纯代码实现自定义快捷键,分享一下。

不废话,直接上代码:

        /// <summary>
        /// 创建快捷键
        /// </summary>
        /// <param name="customKey">快捷键如F1 等</param>
        private void BuildingInputBinding(string customKey)
        {
            if (string.IsNullOrEmpty(customKey))
            {
                return;
            }
            RoutedUICommand routcmd =new RoutedUICommand("Choice Discount Type", 

                  "ChoiceDiscountType_" + customKey,

                    typeof(TollGate));  //TollGate是你设置快捷键的窗体
            
            InputBinding ibd = new InputBinding(routcmd, new KeyGesture((Key)Enum.Parse(typeof(Key), customKey)));

            ibd.CommandTarget = this.cbDisType;  //设置目标元素
            this.InputBindings.Add(ibd);
            CommandBinding ChoiceDiscountType = new CommandBinding(
                    routcmd,
                    OpenCmdExecuted,
                    OpenCmdCanExecute);
            
            this.CommandBindings.Add(ChoiceDiscountType);


        }
        /// <summary>
        /// 路由事件判断是否应该执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
           //加入自己的执行条件
            e.CanExecute = true;
        }


        /// <summary>
        /// 路由事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenCmdExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            //你的代码


        }

0 0