开发者

KeyCode and keyboard layout and language

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

How can I test for this key un开发者_如何学Cder 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.


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.


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();
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜