C# 如何将字符串转换为键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19077797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:01:28  来源:igfitidea点击:

How to convert string to Keys

c#.netwinformskeytypeconverter

提问by gbk

try to implement combination of keypressing for my programm currently can detect required keypressed (in this postdescribed how) but only predefined in code, but I want to store setting in condig file then read it and use if pressed.

尝试为我的程序实现按键组合目前可以检测所需的按键(在这篇文章中描述了如何)但仅在代码中预定义,但我想将设置存储在 condig 文件中,然后读取它并在按下时使用。

Now can store it, and read as string - currently try to convert readed string to Keys, using next code:

现在可以存储它,并读取为字符串 - 当前尝试Keys使用下一个代码将读取的字符串转换为 :

Storing in config file:

存储在配置文件中:

<add key="open" value="ControlKey,N"
<add key="close" value="ControlKey,Q" />
<add key="clear" value="ControlKey,D" />
<add key="settings" value="ControlKey,S" />
<add key="colorKey" value="ControlKey,K" />
<add key="fontKey" value="ShiftKey,T" />
<add key="defaultKey" value="ControlKey,P" />

and using it

并使用它

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        TypeConverter converter = TypeDescriptor.GetConverter(typeof(Keys));
        string[] keyValueTemp;

        keyValueTemp = cm.GetValueString("open").ToString().Split(',');
        string key1 = keyValueTemp[0];
        string key2 = keyValueTemp[1];

        Keys keys1 = (Keys)converter.ConvertFromString(key1);
        Keys keys2 = (Keys)converter.ConvertFromString(key2);

        if (ModifierKeys == keys1 && e.KeyCode == keys2)
        {
            string keyPressed = e.KeyCode.ToString();
            MessageBox.Show(keyPressed);
        }
    }

But, has next result -

但是,有下一个结果——

enter image description hereSo - as you see - this convert control Key to Shiftkey, also try to use code if (ModifierKeys.ToString() == keyValueTemp[0] && e.KeyCode.ToString() == keyValueTemp[1]), but it's not work too.

在此处输入图片说明所以 - 如你所见 - 将 control Key 转换为 Shiftkey,也尝试使用 code if (ModifierKeys.ToString() == keyValueTemp[0] && e.KeyCode.ToString() == keyValueTemp[1]),但它也不起作用。

if use this code

如果使用此代码

        if (e.Modifiers == Keys.Control && e.KeyCode == Keys.N)
        {
            string keyPressed = e.KeyCode.ToString();
            MessageBox.Show(keyPressed);
        }

all works

所有作品

Q: how can i convert string to Keys and compare it with keyPressed events?

问:如何将字符串转换为 Keys 并将其与 keyPressed 事件进行比较?

EDIT

编辑

So found my mistake

所以发现我的错误

Keys key = (Keys)converter.ConvertFromString(keyValueTemp[0]);
Keys key2 = (Keys)converter.ConvertFromString(keyValueTemp[1]);
if (e.Modifiers == key && e.KeyCode == key2)
   {
       MessageBox.Show(e.KeyCode.ToString());
   }

forget to add e- from event handler

忘记添加e- 来自事件处理程序

another way - as written by AccessDenied

另一种方式 - 正如AccessDenied所写

 Keys key = (Keys)Enum.Parse(typeof(Keys), keyValueTemp[0], true);

采纳答案by Kurubaran

Key comparision is done with enumerations, So what you have to do is a String to Enumconversion.

键比较是用枚举完成的,所以你要做的就是String to Enum转换。

if (e.Modifiers == (Keys)Enum.Parse(typeof(Keys), "keys1", true)
    && e.KeyCode == (Keys)Enum.Parse(typeof(Keys), "keys2", true))
{
    string keyPressed = e.KeyCode.ToString();
    MessageBox.Show(keyPressed);
}

回答by Muhammad Umar

Keys key;
Enum.TryParse("Enter", out key);

回答by Sriram Sakthivel

I'll suggest you not to store keys in config as "ControlKey,N", rather store its value.

我建议您不要将配置中的键存储为“ControlKey,N”,而是存储其值。

 Keys openKey = Keys.ControlKey | Keys.N;
 int value = (int)openKey;//95

It integer representation is 95, So store in app.config as

它的整数表示是95,所以在 app.config 中存储为

<add key="open" value="95">//ControlKey|N

Keys open = (Keys)int.Parse(cm.GetValueString("open").ToString());

Here open will be Keys.ControlKey | Keys.N

这里开放将是 Keys.ControlKey | Keys.N

Then you can compare easily against e.KeyData

然后你可以很容易地与 e.KeyData

if(e.KeyData == open)
{
    //Control + N pressed
}

回答by Markus1980Wien

I am doing it the following way. In app.config file I have the following

我正在按照以下方式进行操作。在 app.config 文件中,我有以下内容

<add key="KeyboardShortcut" value="Control+M" />

and to use it in my code-file

并在我的代码文件中使用它

public System.Windows.Forms.Keys ShortCutKeys
{
    get
    {
        string keyboardShortcut = ConfigurationManager.AppSettings["KeyboardShortcut"];
        System.Windows.Forms.Keys retval = System.Windows.Forms.Keys.None;

        if (!string.IsNullOrEmpty(keyboardShortcut))
        {
            try
            {
                 System.Windows.Forms.KeysConverter kc = new System.Windows.Forms.KeysConverter();
                 retval = (System.Windows.Forms.Keys)kc.ConvertFromInvariantString(keyboardShortcut);
            }
            catch (Exception ex)
            {
                log.Info(ex.ToString());           
            }
       }
       return retval;
    }
}

And to detect if the key was pressed

并检测是否按下了键

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    try
    {           
        if (this.ShortCutKeys != Keys.None && (keyData & this.ShortCutKey) == this.ShortCutKey)
        {
            this.Execute_Plugin();
        }
    }
    catch(Exception ex)
    {
        log.Error(ex.ToString());
    }
}

回答by overcomer

In addition of Muhammad Umar answer.

除了穆罕默德·奥马尔的回答。

For version 3.5 of .NET or before you can do

对于 .NET 3.5 版或之前的版本

Keys key = Enum.Parse(typeof(Keys), "Enter");

Be carefull to catch exceptions.

小心捕捉异常。