简体   繁体   English

将KeyDown键转换为一个字符串C#

[英]Convert KeyDown keys to one string C#

I have magnetic card reader, It emulates Keyboard typing when user swipes card. 我有磁卡读卡器,用户刷卡时模拟键盘输入。 I need to handle this keyboard typing to one string, when my WPF window is Focused. 当我的WPF窗口是Focused时,我需要处理这个键盘输入到一个字符串。 I can get this typed Key list, but I don't know how to convert them to one string. 我可以得到这个键入的键列表,但我不知道如何将它们转换为一个字符串。

private void Window_KeyDown(object sender, KeyEventArgs e)
{
   list.Add(e.Key);
}

EDIT : Simple .ToString() method not helps. 编辑 :简单.ToString()方法没有帮助。 I've tried this already. 我已经尝试过了。

Rather than adding to a list why not build up the string: 而不是添加到列表中为什么不建立字符串:

private string input;

private bool shiftPressed;

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
    {
        shiftPressed = true;
    }
    else
    {
        if (e.Key >= Key.D0 && e.Key <= Key.D9)
        {
            // Number keys pressed so need to so special processing
            // also check if shift pressed
        }
        else
        {
            input += e.Key.ToString();
        }
    }
}

private void Window_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
    {
        shiftPressed = false;
    }
}

Obviously you need to reset input to string.Empty when you start the next transaction. 显然,当您启动下一个事务时,需要将input重置为string.Empty

...or you can try this: ......或者你可以试试这个:

string stringResult = "";
list.ForEach(x=>stringResult+=x.ToString());

EDIT: After good Timur comment I decided to suggest this: 编辑:经过Timur的好评,我决定建议:

you can use keyPress event to everything like this: 你可以使用keyPress事件来做这样的事情:

string stringResult = "";
private void Window_KeyPress(object sender, KeyPressEventArgs e)
{
    stringResult += e.KeyChar;
}

You could have a member variable which is a StringBuilder . 你可以有一个成员变量,它是一个StringBuilder

something like 就像是

class A
{
    StringBuilder _contents = new StringBuilder();

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        _contents.Append(e.Key.ToString());
    }
}

You would have to create a new StringBuilder each time a new card was swiped and then to get the string you would use _contents.ToString(); 每次刷卡时都需要创建一个新的StringBuilder,然后获取你将使用的字符串_contents.ToString();

String combined = String.Empty; String combined = String.Empty;

private void Window_KeyDown(object sender, KeyEventArgs e)
{
   combined = combined + e.Key.ToString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM