我一般不熟悉Visual Studio,.Net和Windows,但我们的任务是编写一个具有Windows窗体的程序。该程序现在几乎可以使用了,但是我遇到了困扰我的事情。
我编写了以下函数,只允许将数字输入TextBox
:
private: System::Void tbPDX_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
if(e->KeyChar == '.'){
if( this->tbPDX->Text->Contains(".") && !this->tbPDX->SelectedText->Contains(".") )
e->Handled = true;
}
// Allow negative numbers
else if(e->KeyChar == '-'){
if((!System::String::IsNullOrWhiteSpace(this->tbPDX->Text)) && !(this->tbPDX->Text->IndexOf('-') == -1))
e->Handled = true;
}
// Accept only digits ".", "-" and the Backspace character
else if(!Char::IsDigit(e->KeyChar)&& e->KeyChar != 0x08){
e->Handled = true;
}
}
这适用于小数点,但它不适用于否定。例如,我可以输入0-.0
。有没有办法检查输入的字符的位置是否在String^
的开头?从我所看到的,只有在输入角色之前才能看到字符串?
答案 0 :(得分:1)
经过一些调整后,我最终使用了Hans Passant建议的方法。
这是我的最终功能:
private: System::Void tbPDX_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
if(e->KeyChar == '.'){
if( this->tbPDX->Text->Contains(".") && !this->tbPDX->SelectedText->Contains(".") )
e->Handled = true;
}
// Allow negative numbers
else if(e->KeyChar == '-' && !(this->tbPDX->Text->Contains("-"))){
e->Handled = true;
tbPDX->Text = "-" + tbPDX->Text;
}
// Accept only digits ".", "-" and the Backspace character
else if(!Char::IsDigit(e->KeyChar)&& e->KeyChar != 0x08){
e->Handled = true;
}
}