ravi.joshi53's picture

Invoking OpenTK from Windows Form

I am invoking OpenTK app from a Windows Form. The form is having a start button. The OpenTK GameWindow runs when start button has been clicked. Following is the code-

private void startButton_Click(object sender, EventArgs e)
{
    using (MyGameWindow game = new MyGameWindow(width, height))
        game.Run(60);
}

The game uses Cgen.Audio as audio library. Also the game has an exit button, which simply close this GameWIndow by calling Exit(); method. I noticed that after clicking on exit button when I click on start button again to start the GameWindow, OpenTK behaves abnormally. Textures are not rendered perfectly and audio is horrible. It seems some objects are not disposed properly.

Please suggest me a way to solve it.

-
Thanks


Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

In general, you should avoid mixing two different GUI toolkits in the same process. The cross-platform solution is to launch your GameWindow in a new process. On Windows, it will also work if you launch the GameWindow in a new thread with ApartmentState.STA.

Combining WinForms and GameWindow on the same thread will result in undefined behavior.

ravi.joshi53's picture

Ok...
Can you please post a sample code here? How to use ApartmentState.STA?

the Fiddler's picture

From one of my projects:

        readonly object launcher_lock = new object();
        Thread game_thread;
        private void Form1_Load(object sender, EventArgs e)
        {
            lock (launcher_lock)
            {
                if (game_thread == null)
                {
                    // Game is not running, launch it in a new thread
                    game_thread = new Thread(() =>
                    {
                        using (var game = new GameWindow())
                        {
                            game.Run(60);
                        }
                        game_thread = null;
                    });
 
                    game_thread.SetApartmentState(ApartmentState.STA);
                    game_thread.Start();
                }
                else
                {
                    // Game is already running
                }
            }
        }
ravi.joshi53's picture

Fiddler, I still showing the old behavior. The audio is playing horribly and graphics are not updating. Actually, the GameWindow invokes a thread from its thread. So is it correct?
game_thread.SetApartmentState(ApartmentState.STA);

the Fiddler's picture
Quote:

Actually, the GameWindow invokes a thread from its thread.

Make sure to exit that thread when you close the GameWindow.