【问题标题】:Handling of keyboard shortcut in .NET is too slow for some users对于某些用户来说,在 .NET 中处理键盘快捷键太慢了
【发布时间】:2012-07-26 11:07:56
【问题描述】:

我的应用程序中有一些键盘处理代码,例如,Ctrl + C

我的应用程序的一些用户在键盘上非常快(按下 Ctrl 并立即按下 C 并释放两者),因此事件处理程序不会得到它足够快。

该效果同时出现在Windows FormsWPF 上。

请查看此 Windows 窗体示例。如果您对如何固定东西有任何建议,我会很高兴。您可以使用此示例来重现它(但您必须要快)。

我想知道其他应用程序是如何编程的。以 Visual Studio 为例。在那里,您输入该快捷方式的速度无关紧要。它的行为符合预期。

示例:我有一个窗口,其中包含一个面板,当快捷方式成功捕获时,该面板会在 100 毫秒内变为红色。

using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KeyboardShortcutTest
{
    public partial class Form1 : Form
    {
        private TaskScheduler _uiScheduler;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            KeyUp += Form1_KeyUp;
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.C)
            {
                ColorizePanelRed(_displayPanel);
            }
        }

        private void ColorizePanelRed(Panel panel)
        {
            Color c = panel.BackColor;

            Task.Factory.StartNew(() => { panel.BackColor = Color.Red; }, CancellationToken.None, TaskCreationOptions.None, _uiScheduler)
                .ContinueWith(t => { Thread.Sleep(100); })
                .ContinueWith(t => { panel.BackColor = c; }, _uiScheduler);
        }
    }
}

【问题讨论】:

    标签: .net wpf winforms keyboard-shortcuts


    【解决方案1】:

    问题可能是某些用户在松开 C 键之前太快松开了 Ctrl。我认为捕获 KeyDown 事件而不是 KeyUp 将是避免这些问题的好方法。

    【讨论】:

    • 感谢您的回答。处理 KeyUp 事件就可以了。
    猜你喜欢
    • 2012-10-30
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多