Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

http://www.morethannothing.co.uk/2009/02/using-vkkeyscanex-to-find-out-what-keys-should-be-pressed-to-produce-a-character/ might help.

[Edit] It should be noted that regardless, handling KeyPressed is probably a better tactic.

Use KeyPress event

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        int keyValue = e.KeyChar;
        textBox1.Text = Convert.ToChar(keyValue).ToString();
    }
        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();
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top