C++/CLI:如何从主函数控制 WinForms?
C++/CLI: How to control WinForms from main function?
我正在尝试在主函数而不是窗体的 header 中实现界面控件。我正在尝试这样做,因为我必须使用多种形式,从另一种形式调用一种形式,相反,在它们之间传递信息。
例如,我在 MyForm 中有 button1,在 MyForm 的 header 中,我通过代码对它进行操作:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
//stuff
}
如何从主函数执行相同的操作?我应该包括什么,要使用什么命名空间,代码会是什么样子?我的主要 .cpp 现在看起来是这样的:
#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
int main(array < String^>^ args)
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(0);
Project1::MyForm form;
Application::Run(%form);
}
谢谢!
C++/CLI 仍然是 C++ 而不是 C#:您可以在 .cpp 中而不是在 class 定义中实现表单的方法。这不是巫师为你做的。
//MyForm.h
namespace Project1
{
class MyForm
{
//...
//Somewhere in the MyForm class definition
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e);
};
}
并且在 cpp 中:
//MyForm.cpp
using namespace System;
namespace Project1
{
Void MyForm::button1_Click(Object^ sender, EventArgs^ e) {
//stuff
}
}//namespace Project1
至于您在多个表单之间进行通信的问题,您可以选择更 Document/View(或 Model/View/Controller)的方法,将您的状态放在一个共享对象中,该共享对象在修改时提供事件,并且让您的表单监听这些事件以在状态更改时自行更新。
我正在尝试在主函数而不是窗体的 header 中实现界面控件。我正在尝试这样做,因为我必须使用多种形式,从另一种形式调用一种形式,相反,在它们之间传递信息。 例如,我在 MyForm 中有 button1,在 MyForm 的 header 中,我通过代码对它进行操作:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
//stuff
}
如何从主函数执行相同的操作?我应该包括什么,要使用什么命名空间,代码会是什么样子?我的主要 .cpp 现在看起来是这样的:
#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
int main(array < String^>^ args)
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(0);
Project1::MyForm form;
Application::Run(%form);
}
谢谢!
C++/CLI 仍然是 C++ 而不是 C#:您可以在 .cpp 中而不是在 class 定义中实现表单的方法。这不是巫师为你做的。
//MyForm.h
namespace Project1
{
class MyForm
{
//...
//Somewhere in the MyForm class definition
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e);
};
}
并且在 cpp 中:
//MyForm.cpp
using namespace System;
namespace Project1
{
Void MyForm::button1_Click(Object^ sender, EventArgs^ e) {
//stuff
}
}//namespace Project1
至于您在多个表单之间进行通信的问题,您可以选择更 Document/View(或 Model/View/Controller)的方法,将您的状态放在一个共享对象中,该共享对象在修改时提供事件,并且让您的表单监听这些事件以在状态更改时自行更新。