在MFC裡需要獲取文本輸入時
在
繼承TextBox並覆蓋其CreateParams屬性
自行監聽TextBox的KeyDown事件
使用第三方編寫的繼承自TextBox的控件
光是CodeProject上就有好幾個與這個相關的實現
Validating Edit Controls
A numeric textbox with a twist
Numeric TextBox
使用MaskedTextBox 控件
使用NumericUpDown控件
下面對這幾種解決方法的其中一些稍微討論一下
一
使用這種方法的NumericTextBox的實現(代碼的第
C#代碼
public class NumericTextBox : System
{
private const int ES_NUMBER =
protected override System
get {
System
cp
return cp;
}
}
}
#region use case code sample
sealed class TestForm : System
{
private NumericTextBox m_ntxt;
public TestForm() {
InitializeComponent();
}
private void InitializeComponent() {
this
this
this
this
this
}
[System
static void Main(string[] args) {
System
System
System
}
}
#endregion
運行程序
(截圖反映的是在我的簡體中文Windows XP上的運行效果
如果這個文本框已經能滿足需求
二
可以參考CodeProject上Numeric TextBox
最簡單來說類似這樣
C#代碼
using System;
using System
using System
sealed class TestForm : Form
{
private TextBox m_textBox;
private bool m_nonNumberEntered = false;
public TestForm() {
InitializeComponent();
}
private void InitializeComponent() {
this
this
this
this
this
this
this
}
private void m_textBox_KeyDown(object sender
// Initialize the flag to false
m_nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard
if (e
// Determine whether the keystroke is a number from the keypad
if (e
// Determine whether the keystroke is a backspace
if(e
// A non
// Set the flag to true and evaluate in KeyPress event
m_nonNumberEntered = true;
}
}
}
}
private void m_textBox_KeyPress(object sender
// Check for the flag being set in the KeyDown event
if (m_nonNumberEntered) {
// Stop the character from being entered into the control
// since it is non
e
}
}
[STAThread]
static void Main(string[] args) {
Application
Application
Application
}
}
(判斷邏輯來自KeyEventArgs在MSDN文檔上的范例代碼)
得到的文本框外觀與一般的TextBox沒區別
三
使用例子
C#代碼
using System;
using System
sealed class TestForm : Form
{
private MaskedTextBox m_maskedTextBox;
private ToolTip m_toolTip;
public TestForm() {
InitializeComponent();
}
private void InitializeComponent() {
this
this
this
this
this
this
this
this
this
}
private void m_maskedTextBox_InputRejected(object sender
MaskInputRejectedEventArgs e) {
toolTip
toolTip
m_maskedTextBox
}
private void m_maskedTextBox_KeyDown(object sender
m_toolTip
}
[STAThread]
static void Main(string[] args) {
Application
Application
Application
}
}
這段代碼是手寫的
輸入內容(可以看到分隔符都不需要自己寫了
輸入內容不符合Mask屬性指定的模式時
四
C#代碼
using System;
using System
using System
sealed class TestForm : Form
{
private NumericUpDown m_numericUpDown;
public TestForm() {
InitializeComponent();
}
private void InitializeComponent() {
this
this
this
this
this
this
this
this
}
[System
static void Main(string[] args) {
Application
Application
Application
}
}
這段代碼是手寫的
NumericUpDown的內容的值可以用Value屬性來設置或獲取
截圖
From:http://tw.wingwit.com/Article/program/net/201311/11675.html