从Windows窗体外部(从int WINAPI WinMain)调用Windows窗体方法

call a Windows Forms method from outside Windows Forms (from int WINAPI WinMain)

本文关键字:窗体 Windows 方法 WinMain 调用 int 外部 WINAPI      更新时间:2023-10-16

为了将用户界面类(一个Windows窗体类)与程序的其余部分分离,我试图从int WINAPI WinMain()调用Windows窗体方法

例如,我正在尝试以下操作:

int WINAPI WinMain(HINSTANCE hInstance, 
    HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{   
    Application::EnableVisualStyles();
    UserInterface1 ^myInterface = gcnew UserInterface1();   
    String ^ picture1 = "img1";
    String ^ picture2 = "img2";
    Application::Run(myInterface); 
    Bitmap^ B = gcnew Bitmap (512,512);
    //user defined class that reads an image from a file
    PImage PI(picture1);
    //a Windows Forms method that updates the image displayed in a pictureBox element
    myInterface->ModifyDisplay (B, PI);
    //user defined class that reads an image from a file
    PImage PI2(picture2);
    //a Windows Forms method that updates the image displayed in a pictureBox element
    myInterface->ModifyDisplay (B, PI2);
    return 0;
}

不用说,它并没有像现在这样工作,我不确定我试图做的事情是否可行,因为我对.Net编程还很陌生。

它看起来像"Application::Run(myInterface);"在完成它必须做的事情之前不会返回,这不是

这不是什么。Application::Run最重要的是启动Windows事件消息泵。这个事件循环使您的应用程序保持活动和运行。Application::Run将仅在该循环退出时返回。

当您关闭主窗体或试图关闭任务管理器等的流程时,事件循环通常会退出。

这意味着当Application::Run返回时,您的myInterface表单已经关闭,这使得它下面的其余代码变得无用。您可以将该代码移动到类似FormLoad事件中。

确切地说,"Application::Run()"之后的代码将在表单关闭时运行。我建议您创建两个表单,例如"Form1"answers"Form2"(使用线程是另一种方式,但这更容易)。

使用"Form1"作为隐藏的基本表单,它用于通过从文件中获取图像来更新应用程序。

使用"Form2"作为UserInterface1。要做到这一点,如果你是新手,你应该在"Form1"中运行"Form2",如下所示:

// Inside Form1.
#include "Form2.h"
Form2 ^openForm2 = gcnew Form2();
openForm2->Show();

最后,您可以在Form1中运行ModifyDisplay函数。

openForm->ModifyDisplay();