首页 > 解决方案 > C++/CLI Winform - 是否可以有多个文本框的 1 个事件处理程序

问题描述

我试图通过使用我从另一篇文章中找到的这个函数来将用户输入限制为浮点数或整数。

private: System::Void keypressValidation(System::Windows::Forms::TextBox^ textBox, System::Windows::Forms::KeyPressEventArgs^ e) {
        // Only allow 1 decimal point
        if (e->KeyChar == '.')
        {
            if (textBox->Text->Contains(".") && !textBox->SelectedText->Contains("."))
            {
                e->Handled = true;
            }
        }
        // Accepts only digits and Backspace keypress
        else if (!Char::IsDigit(e->KeyChar) && e->KeyChar != 0x08)
        {
            e->Handled = true;
        }
    }

现在我的 UI 上有 8 个文本框,我为每个单独的文本框创建了 8 个不同的按键事件处理程序。

private: System::Void txtN3_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
        keypressValidation(txtN3, e);
    }
    private: System::Void txtN2_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
        keypressValidation(txtN2, e);
    }
    private: System::Void txtN1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
        keypressValidation(txtN1, e);
    }
    private: System::Void txtN0_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
        keypressValidation(txtN0, e);
    }
    private: System::Void txtD3_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
        keypressValidation(txtD3, e);
    }
    private: System::Void txtD2_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
        keypressValidation(txtD2, e);
    }
    private: System::Void txtD1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
        keypressValidation(txtD1, e);
    }
    private: System::Void txtD0_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
        keypressValidation(txtD0, e);
    }

但后来在我的项目中,我将拥有大约 64 个文本框,我发现为每个文本框都设置一个事件处理程序太乏味了。有没有一种方法可以使它更紧凑,例如只有一个事件处理程序用于多个文本框?

标签: winformstextboxc++-cli

解决方案


我的首选方法是遍历表单中的所有文本框并绑定单个事件处理程序。以下是 C++/CLI 中的示例代码:

private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
    for each (Control ^ ctrl in this->Controls)
    {
        if (ctrl->GetType() == TextBox::typeid)
        {
            ctrl->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form1::textBox1_KeyPress);
        }
    }
}

private: System::Void textBox1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e)
{

}

推荐阅读