Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert KeyDown keys to one string C#

Tags:

c#

.net

wpf

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. 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. I've tried this already.

like image 960
Timur Mustafaev Avatar asked Nov 29 '11 12:11

Timur Mustafaev


2 Answers

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.

like image 124
ChrisF Avatar answered Oct 19 '22 21:10

ChrisF


...or you can try this:

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

EDIT: After good Timur comment I decided to suggest this:

you can use keyPress event to everything like this:

string stringResult = "";
private void Window_KeyPress(object sender, KeyPressEventArgs e)
{
    stringResult += e.KeyChar;
}
like image 1
Renatas M. Avatar answered Oct 19 '22 20:10

Renatas M.