【问题标题】:How to call a method from WindowsForms in Monogame?如何在 Monogame 中从 WindowsForms 调用方法?
【发布时间】:2019-04-25 08:15:59
【问题描述】:

您好,我目前正在做一个项目。我的主要表单是一个表单,每当我单击一个按钮时,monogame 程序就会启动。这行得通。

现在我在主表单中创建了一个方法,我想将 bool 传递给 monogame 表单。

主窗体方法:(如果选中复选框,monogame 应该绘制天际线)

public bool skyCheck()
    {
        if (checkBox1.Checked == true)
        {
            sky = true;                
        }
        else
        {
            sky = false;
        }
        return sky;

单游戏检查:

if (skyCheck() == true)
        {
            DrawSky();
        }

这给了我名称“skyCheck”在当前上下文中不存在。

【问题讨论】:

  • 您发布的代码与您的问题无关。听起来您在尝试使用它的不同类中声明 skyCheck() 。您需要提供更多信息,希望有人帮助您。

标签: winforms methods monogame


【解决方案1】:

我制作了一个控件,它将单人游戏嵌入到表单中,这样就不必运行单独的程序。它不是你看到的普通嵌入式单人游戏,它只给你一个图形设备,没有更新或游戏方法。这是一个嵌入的实际单人游戏。

这不是您问题的根源,但它可以帮助您解决问题并让您的程序变得更好。

Here 是源代码,自述文件中包含有关如何使用它的一些简短文档

【讨论】:

    【解决方案2】:

    将表单的引用传递给 Game1 的构造函数:

    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
    
        //Change the Form1 to the name of the form class.
        Form1 form;
    
    //...
    
        public Game1(Form1 form)
        {
           this.form = form;
           graphics = new GraphicsDeviceManager(this);
           Content.RootDirectory = "Content";
        }
    //...
    // I will assume the DrawSky() should be called in Draw.
    
        protected override void Draw(GameTime gameTime)
        {
    //...
           if (form.skyCheck()) // the "== true" is redundant.
           {
               DrawSky();
           }
    //...
        }
    }
    

    以下代码通常位于Program.cs 中,但作为窗口窗体应用程序,此代码将位于启动游戏的窗体中:

    game = new Game1(this); // where "this" refers to the current form
    game.Run();
    

    请注意混合 Windows 窗体和 MonoGame 的注意事项:

    1. 表单的消息泵和游戏在同一个线程中运行。表格上的任何停顿都会导致游戏滞后。
    2. 会有性能损失。
    3. 确保在卸载表单之前正确关闭游戏,以确保正确清理资源。

    可以启动另一个线程来运行游戏(从而绕过前两个警告),但是,两个线程之间的所有通信都必须是线程安全的。布尔分配和整数分配(=

    需要两个线程中的退出协调。

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多