Windows窗体显示与显示对话框

Windows Form Show vs ShowDialog

本文关键字:显示 对话框 Windows 窗体      更新时间:2023-10-16

我有一个小应用程序,正在尝试为windows创建。我遇到了一个混合用于处理一些数据的后台线程的问题。这个后台引擎需要有人更新应用程序gui(一个windows窗体)并从中获取信息

这是基本的应用程序主界面。

int main() {
Engine engine;
Gui g;
engine.run(); // creates a new thread for engine logic
g.ShowDialog();
bool running = false;
while(1)
{
    // Update gui with information from the engine
    g.update(engine.GetState());
    // transition to running
    if(g.isRunning() && !running)
    {
        engine.play();
        running = true;
    }
    // transition to stopped
    else if(!g.isRunning() && running)
    {
        engine.stop();
        running = false;
    }
}
}

我的主要问题来自于桂班被管理的事实。请参阅下面的类声明。

public ref class Gui : public System::Windows::Forms::Form

我真的不能把这两件事混合在一起,一开始我只想把引擎扔到Gui中,但这不起作用,因为它是不受管理的。

您会注意到,这里的问题是调用ShowDialog(),因为这会使对话框处于模态状态,之后不会执行任何代码。但是,如果我使用Show()。。。桂根本不更新或处理任何输入。

解决方案:

我在Gui类中创建了一个后台工作程序,所以引擎包含在Gui中,但在另一个线程上运行。

    void InitializeBackgoundWorker()
    {
        this->backgroundWorker1 = gcnew System::ComponentModel::BackgroundWorker;
        backgroundWorker1->DoWork += gcnew DoWorkEventHandler( this, &Gui::backgroundWorker1_DoWork );
        backgroundWorker1->RunWorkerAsync( );
    }
    delegate void UpdateCallback(int hp, int maxhp);
    void UpdateGui(int hp, int maxhp)
    {
        this->playerHealthBar->Value = ((float)(hp)/(float)(maxhp) * 100.0f);
    };
    void backgroundWorker1_DoWork( Object^ sender, DoWorkEventArgs^ e )
    {
        aBotEngine engine;
        while(true)
        {
            engine.runnable(NULL);
            array<Object^>^args = gcnew array<Object^>(2);
            args[0] = engine.getPlayerHp();
            args[1] = engine.getPlayerMaxHp();
            this->playerHealthBar->Invoke(gcnew UpdateCallback(this, &Gui::UpdateGui), args);
        }
    };

据我所知,这是让后台线程更新windows窗体的正确方法。我相信这不是唯一的方法。

void InitializeBackgoundWorker()
{
    this->backgroundWorker1 = gcnew System::ComponentModel::BackgroundWorker;
    backgroundWorker1->DoWork += gcnew DoWorkEventHandler( this, &Gui::backgroundWorker1_DoWork );
    backgroundWorker1->RunWorkerAsync( );
}
delegate void UpdateCallback(int hp, int maxhp);
void UpdateGui(int hp, int maxhp)
{
    this->playerHealthBar->Value = ((float)(hp)/(float)(maxhp) * 100.0f);
};
void backgroundWorker1_DoWork( Object^ sender, DoWorkEventArgs^ e )
{
    aBotEngine engine;
    while(true)
    {
        engine.runnable(NULL);
        array<Object^>^args = gcnew array<Object^>(2);
        args[0] = engine.getPlayerHp();
        args[1] = engine.getPlayerMaxHp();
        this->playerHealthBar->Invoke(gcnew UpdateCallback(this, &Gui::UpdateGui), args);
    }
};