2

I need to include the asterisk as an allowable entry on a text box.

How can I test for this key under the KeyDown event regardless of the keyboard layout and language?

Ignoring the numeric keypad, with the Portuguese QWERTY layout this key can be tested through Keys.Shift | Keys.Oemplus. But that will not be the case for other layouts or languages.

Alexandre Bell
  • 3,141
  • 3
  • 30
  • 43
  • Possible duplicate of [in keydown event get charecter in different language](https://stackoverflow.com/questions/10110073/in-keydown-event-get-charecter-in-different-language) – Liam Oct 22 '19 at 15:23

3 Answers3

2

You are using the wrong event, you should be using KeyPressed. That fires when the user presses actual typing keys. KeyDown is useless here, the virtual key gets translated to a typing key according to the keyboard layout. Hard to guess what that might be unless you translate the keystroke yourself. That's hard.

Some code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
  string allowed = "0123456789*\b";
  if (allowed.IndexOf(e.KeyChar) < 0) e.Handled = true;
}

The \b is required to allow the user to backspace.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • I'm using the KeyPress event to handle this. Was wondering about the possibility of using KeyDown instead. But your answer reveals it's not possible. Thanks. – Alexandre Bell Dec 06 '09 at 00:22
0

Use KeyPress event

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        int keyValue = e.KeyChar;
        textBox1.Text = Convert.ToChar(keyValue).ToString();
    }
0
        InitializeComponent();

        //SET FOCUS ON label1 AND HIDE IT
        label1.Visible = false;
        label1.Select();
    }

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        int keyValue = e.KeyChar;
        textBox1.Text = Convert.ToChar(keyValue).ToString();

        if (keyValue == 13) // DETECT "ENTER"
        {
        StreamWriter writelog = File.AppendText(@"C:\keylogger.log");
        writelog.Write(Environment.NewLine);
        writelog.Close();
        }
        else
        {
        StreamWriter writelog = File.AppendText(@"C:\keylogger.log");
        writelog.Write(Convert.ToChar(keyValue).ToString());
        writelog.Close();
        }
    }
  • Please think about improving your answer by adding some description on why this will work. Code dumps are rarely ever a use – David Medenjak Feb 06 '16 at 11:47
  • That said, it is still an attempt to answer the question - [somebody must have flagged this post](http://stackoverflow.com/review/low-quality-posts/11164679) for it to appear in the review queue. – Wai Ha Lee Feb 06 '16 at 14:44