开发者

Modify a character before it reaches a TextBox

I am creating a numeric text box and I want the numpad decimal character mapped to CultureI开发者_如何学运维nfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator like Excel does.

Is there a way to modify (substitute) a key before it is interpreted by a TextBox?

My current strategy is this:

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Decimal)
    {
        e.Handled = true;
        e.SuppressKeyPress = true;

        int selectionStart = SelectionStart;

        Text = String.Concat(
            Text.Substring(0, selectionStart),
            CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator,
            Text.Substring(SelectionStart + SelectionLength)
        );

        Select(selectionStart + 1, 0);
    }
    else
    {
        base.OnKeyDown(e);
    }
}


Yes, you can catch the WM_CHAR message by overriding WndProc():

using System;
using System.Windows.Forms;

class MyTextBox : TextBox {
    protected override void WndProc(ref Message m) {
        if (m.Msg == 0x102 && m.WParam.ToInt32() == '.') {
            m.WParam = (IntPtr)'/';   // test only
        }
        base.WndProc(ref m);
    }
}

Beware that you've also got a problem with the clipboard (Ctrl+V). That's message WM_PASTE, 0x302. A possible workaround is:

    if (m.Msg == 0x302 && Clipboard.ContainsText()) {
        var txt = Clipboard.GetText();
        txt = txt.Replace('.', '/');
        this.SelectedText = txt;
        return;                        
    }


Instead of replacing the entire Text-property, you could set the SelectedText-property to the separator:

if (e.KeyCode == Keys.Decimal)
{
    e.Handled = true;
    e.SuppressKeyPress = true;
    SelectedText = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
}
else base.OnKeyDown(e);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜