有没有简单的方法来检查重复的快捷键?

时间:2014-04-01 14:00:22

标签: c# winforms visual-studio-2010

我最近遇到了Winforms应用程序的情况,其中一个快捷键正在触发多个事件,因为相同的键被映射到多个控件。有一种简单的方法可以在应用程序中搜索这样的重复键吗?我认识到,对于不可能发生的情况,例如相互排斥的对话共享相同的密钥,可能会出现误报,但至少有一个起点可能会很好。

目前我能想到的最好的办法是在资源文件中搜索.ShortcutKeys数据,然后处理结果,但这似乎有点过分了。

1 个答案:

答案 0 :(得分:1)

尝试使用System.Windows.Automation库枚举快捷方式。这是一个查看任务管理器的快速而肮脏的示例。您必须添加对UIAutomationClient和UIAutomationTypes的引用。

class Program
{
    static void Main(string[] args)
    {
        Process process = Process.GetProcessesByName("taskmgr").FirstOrDefault();

        var condition = new PropertyCondition(AutomationElement.ProcessIdProperty, process.Id);

        AutomationElement window = AutomationElement.RootElement.FindFirst(TreeScope.Children, condition);

        AutomationElementCollection descendents = window.FindAll(TreeScope.Descendants, Condition.TrueCondition);

        foreach (var descendent in descendents)
        {
            var foo = descendent as AutomationElement;

            if (!string.IsNullOrWhiteSpace(foo.Current.AcceleratorKey))
                Console.WriteLine(foo.Current.AcceleratorKey);

            if (!string.IsNullOrWhiteSpace(foo.Current.AccessKey))
                Console.WriteLine(foo.Current. AccessKey);
        }

        Console.WriteLine(descendents.Count);

        Console.ReadLine();
    }
}

输出:


Alt + Space

替代+ F

替代+ O

替代+ V

替代+ H

11