【问题标题】:call a Windows Forms method from outside Windows Forms (from int WINAPI WinMain)从 Windows 窗体外部调用 Windows 窗体方法(来自 int WINAPI WinMain)
【发布时间】:2013-07-26 22:44:17
【问题描述】:

为了将用户界面类(一个 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);'在它完成它必须做的事情之前不会返回,这没什么。问题是我不确定如何让它在运行时接受来自 WinMain 的输入(如果可能的话)。
  • 这是非常基础的,请务必从您当地的图书馆中查阅有关 Winforms 编程的书籍。如果您希望运行除 UI 之外的其他代码,则需要使用线程。

标签: c++ .net winforms visual-c++ c++-cli


【解决方案1】:

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

这不是什么。 Application::Run 最重要的是启动 Windows event message pump。这个事件循环是让你的应用程序保持活力和运行的原因。 Application::Run 只会在此循环退出时返回。

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

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

【讨论】:

  • 感谢您的解释。在继续我的项目之前,我肯定会进一步研究 Windows 窗体。
【解决方案2】:

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

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

使用“Form2”作为 UserInterface1。 为此,如果您是新手,您应该像这样在“Form1”中运行“Form2”:

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

最后你可以在Form1中运行ModifyDisplay函数了。

openForm->ModifyDisplay();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多