是否可以选择定义文本并在以后使用它而不是字符串或任何内容,只是作为函数的一部分,但能够在程序中间重新定义它(不发生在预处理器中,但是运行时)?例如,我在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" );
}
其中ps1
和ps2
是 TextBoxes ,我正在使用它来显示灰色'此处为您的文字'字符串并在点击时在TextBox中准备输入(当TB GotFocus
时)清除文本并使输入黑色。考虑到我有9个这样的TextBox,是否有可能用更少的代码来做所有这些?我尝试使用#define ps ps1
和使用该ps的所有内容之外的全局ps_GetFocus()
方法使用相同的代码,但正如您所知,#define
已在预处理器和最后一个定义中完成({{ 1}})甚至在程序启动之前就定义了。
有没有办法在运行时定义非范围的文本?
答案 0 :(得分: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");
}