本文介绍了如何将键盘键与操作相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何激活功能或执行某些操作,或者只需按下与该特定操作相关联的单个按键(就像Photoshop工具一样)来点击按钮?



我不是在谈论按Ctrl / Shift / Alt + Key,我只是想用一个动作分配一个键,就像photoshop工具一样:



E =橡皮擦工具

M =选取框选择工具

V =移动工具

...



如何在C#中实现这一点?

How can I activate functions or perform some actions or just clicking a button by pressing a single key associated with that specific action (just like photoshop tools)?

I'm not talking about pressing Ctrl / Shift / Alt + Key, I just want to assign a single key with an action, just like the photoshop tools works:

E = Eraser tool
M = Marquee selection tool
V = Move tool
...

How can I achieve this in C#?

推荐答案

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
    Keys keyOnly = keyData & ~Keys.Modifiers;
    Keys modifiersOnly = Control.ModifierKeys & (Keys.Shift | Keys.Control | Keys.Alt);
    if (modifiersOnly == 0)
        {
        // Key alone
        switch (keyOnly)
            {
            case Keys.Enter:
                PlaySelected();
                return true;
            }
        }


// maps Keys (KeyData) to Action
private Dictionary<keys,> dctKeysToAction;

// which Controls to handle macro keys
private List<control> KeyOverRideControls;

// scratch variable
private Action KeyAction;

// form-scope key-handling override
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (KeyOverRideControls.Contains(ActiveControl))
    {
        if (dctKeysToAction.TryGetValue(keyData, out KeyAction))
        {
            KeyAction();
            return true;
        }
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

// how a mapping of Control~Key => Action is defined

private void Form1_Load(object sender, EventArgs e)
{
    KeyOverRideControls = new List<control>
    {
        // look for modified key-presses only for these Controls
        dateTimePicker1,
        userControl11
    };

    dctKeysToAction = new Dictionary<keys,>
    {
        {
            Keys.E, () =>
            {
                Console.WriteLine("E");
            }
        },
        Keys.B, () =>
        {
            if (ActiveControl == dateTimePicker1)
            {
                dateTimePicker1.Value = DateTime.Now;
            }
            else
            {
               MessageBox.Show("B in userControl1");
            }
        }
    };
}</control></control>

讨论:



0.因为我们使用唯一的Keys值作为字典中映射到Action的Key,我相信这个对于这种情况,其性能足够。



1.由于在ProcessCmdKey覆盖中作为参数接收的'KeyData值(一个密钥枚举值)对于任何/所有都是唯一的按住键,我们不需要检查控制/ alt / shift键是否关闭。



2.此处的表单有一个UserControl实例,'userControl1和一个DateTimePicker,'dateTimePicker1在设计时位于表单上:只有那些控件将处理由ProcessCmdKey覆盖强制执行的修改后的键评估行为。



3自从UserControl ... unli例如,某个面板将首先吃掉所有击键:如果你在UserControl中有一个TextBox,并且在这里按下了b / B键:UserControl将不会收到该键...除非你修改了ProcessCmdKey中的代码以允许它通过。



4.这里显示的只是划掉表面可以完成。


这篇关于如何将键盘键与操作相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:14