如何在 C++ CLI 中将事件处理程序添加到数组中的按钮?
How to add an event handler to button from array in c++ CLI?
我有一组按钮,我想为它们添加一个事件处理程序。
我的数组:
array<Button^>^ buttons = gcnew array<Button^>(10);
我尝试添加事件处理程序:
private: void tasksButtons_Click(System::Object^ sender, System::EventArgs^ e) {
MessageBox::Show("Lol");
}
private: System::Void main_Load(System::Object^ sender, System::EventArgs^ e) {
int horizontal = 0, vertical = 0;
for each(Button^ i in buttons) {
i = gcnew Button();
i->Text = "i";
i->Width = 20;
i->Height = 20;
horizontal += 20;
i->Location = Point(horizontal, vertical);
this->Controls->Add(i);
i->Click += tasksButtons_Click;
}
}
由于i->Click += tasksButtons_Click
,它给我一个错误。正确的语法是什么?
标准警告:虽然可以使用 C++/CLI 编写应用程序的主体,甚至可以使用 WinForms 在 C++/CLI 中编写 GUI,但不推荐这样做。 C++/CLI 适用于互操作场景:在 C# 或其他 .Net 代码需要与非托管 C++ 交互的情况下,C++/CLI 可以提供两者之间的转换。对于初级开发,如果需要托管代码,建议使用 C# 和 WinForms 或 WPF,如果需要非托管代码,建议使用 C++ 和 MFC。
在 C++/CLI 中,您需要显式实例化委托,使用 C++ 风格的方法引用,并指定调用方法的对象(仅适用于非静态方法)
i->Click += gcnew EventHandler(this, &MyForm::tasksButtons_Click);
// ^^^^^^^^^^^^^^^^^^ instantiate explicitly
// ^^^^ specify the object to use
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ C++-style reference
我有一组按钮,我想为它们添加一个事件处理程序。
我的数组:
array<Button^>^ buttons = gcnew array<Button^>(10);
我尝试添加事件处理程序:
private: void tasksButtons_Click(System::Object^ sender, System::EventArgs^ e) {
MessageBox::Show("Lol");
}
private: System::Void main_Load(System::Object^ sender, System::EventArgs^ e) {
int horizontal = 0, vertical = 0;
for each(Button^ i in buttons) {
i = gcnew Button();
i->Text = "i";
i->Width = 20;
i->Height = 20;
horizontal += 20;
i->Location = Point(horizontal, vertical);
this->Controls->Add(i);
i->Click += tasksButtons_Click;
}
}
由于i->Click += tasksButtons_Click
,它给我一个错误。正确的语法是什么?
标准警告:虽然可以使用 C++/CLI 编写应用程序的主体,甚至可以使用 WinForms 在 C++/CLI 中编写 GUI,但不推荐这样做。 C++/CLI 适用于互操作场景:在 C# 或其他 .Net 代码需要与非托管 C++ 交互的情况下,C++/CLI 可以提供两者之间的转换。对于初级开发,如果需要托管代码,建议使用 C# 和 WinForms 或 WPF,如果需要非托管代码,建议使用 C++ 和 MFC。
在 C++/CLI 中,您需要显式实例化委托,使用 C++ 风格的方法引用,并指定调用方法的对象(仅适用于非静态方法)
i->Click += gcnew EventHandler(this, &MyForm::tasksButtons_Click);
// ^^^^^^^^^^^^^^^^^^ instantiate explicitly
// ^^^^ specify the object to use
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ C++-style reference