我正在创建一个数字文本框,我希望像Excel一样将{numpad十进制字符映射到CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
。
有没有办法在TextBox
解释之前修改(替换)某个键?
我目前的策略是:
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);
}
}
答案 0 :(得分:2)
是的,您可以通过覆盖WndProc()来捕获WM_CHAR消息:
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);
}
}
请注意您的剪贴板也存在问题(Ctrl + V)。这是消息WM_PASTE,0x302。可能的解决方法是:
if (m.Msg == 0x302 && Clipboard.ContainsText()) {
var txt = Clipboard.GetText();
txt = txt.Replace('.', '/');
this.SelectedText = txt;
return;
}
答案 1 :(得分:1)
您可以将SelectedText属性设置为分隔符:
,而不是替换整个Text属性if (e.KeyCode == Keys.Decimal)
{
e.Handled = true;
e.SuppressKeyPress = true;
SelectedText = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
}
else base.OnKeyDown(e);