0

是否可以选择定义文本并稍后使用它而不是作为字符串或任何东西,只是作为函数的一部分,但能够在程序中间重新定义它(定义不在预处理器中进行,但是运行)?例如,我在 C++ Windows 窗体中有以下代码:

private: System::Void ps1_GotFocus(System::Object^  sender, System::EventArgs^  e)
{
    if(this->ps1->Text == L"/ Your text here /") this->ps1->Text = L"";
    this->ps1->ForeColor = System::Drawing::Color::FromName( "Black" );
}

private: System::Void ps2_GotFocus(System::Object^  sender, System::EventArgs^  e)
{
    if(this->ps1->Text == L"/ Your text here /") this->ps1->Text = L"";
    this->ps2->ForeColor = System::Drawing::Color::FromName( "Black" );
}

在哪里ps1ps2TextBoxes,我用它来显示一个灰色的“你的文本在这里”字符串,当在 TextBox 中单击准备输入时(当 TB 时GotFocus)以清除文本并使输入变为黑色。考虑到我有 9 个这样的文本框,是否可以用更少的代码完成所有这些工作?我在使用该 ps 的所有东西之外尝试了相同的代码#define ps ps1和一个全局方法,但正如您所知, s 是在预处理器中完成的,最后一个 define ( ) 甚至在程序启动之前就已经定义了。ps_GetFocus()#defineps ps9

有没有办法在运行时定义非范围文本?

4

1 回答 1

1

只需ps_GotFocus为所有文本框提供一个通用功能,然后使用sender(您必须先将其转换为适当的类型,不知道如何在 .Net C++ 中使用那个奇怪的东西来做到这一点^,也许dynamic_cast会起作用?)而不是各种ps物体。

类似于以下内容:

private: System::Void ps_GotFocus(System::Object^  sender, System::EventArgs^  e)
{
    TypeForYourTextBox^ the_sender = dynamic_cast<TypeForYourTextBox^>(sender);
    // I'm unsure about the previous line but you get the idea
    // You may also want to check that the cast succeeded, ie. the_sender is not null
    if (the_sender->Text == L"/ Your text here /") the_sender->Text = L"";
    the_sender->ForeColor = System::Drawing::Color::FromName("Black");
}
于 2013-04-23T21:43:57.277 回答