C#:WinForms / WPF渲染循环

时间:2015-11-20 15:24:25

标签: c# wpf multithreading winforms sharpgl

我想在WPF窗口或WinForm上创建渲染循环。因此我想使用SharpGL(https://sharpgl.codeplex.com/)。为了使我的循环我做了一个线程:

    public void Run()
    {
        IsRunning = true;
        this.Initialize();

        while (IsRunning)
        {
            Render(/* arguments here */);
            // pausing and stuff
        }

        Dispose();
    }

在渲染中,我想将绘制调用发送到GPU。到目前为止没有问题。但Winforms和WPF需要自己的线程和循环。因此,我不能只使用之前使用的LWJGL(https://www.lwjgl.org/)创建一个Window并使用Java绘制。我必须启动另一个线程,在应用程序中运行Form(我删除了错误处理以使其缩短):

    [STAThread]
    private void HostWinFormsApplication()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(true);

        // get Display
        Display = Engine.MainModule.Resolve<IDisplay>();
        Display.Initialize();
        Display.Closing += (s, e) => Stop();

        Application.Run(Display as Form);
    }

当我的渲染器想要访问我的Form上的OpenGL-Control并使用它时,会发生错误,因为WinForms(和WPF)不希望其他Thread操纵它们的控件。所以也许一个Invoke是一个选项,但这会延迟我的drawcalls并成为瓶颈。 定时器也不是一个选项,因为它不准确和不灵活......而我根本不喜欢它。 并且可以在Window Code中执行所有操作,但我希望应用程序独立于其Display,以便可以更改它。它应该是具有显示器而不是显示器运行应用程序的应用程序。 在LWJGL中,我只能创建并初始化一个Display,然后简单地使用它。唯一要考虑的是更新它,一切都很顺利。 所以我只想在我的渲染线程中创建一个Window并绘制到。如果我这样做,窗口就会变得无法使用和灰色,因为它需要这个.Net-Loop。有没有可能意识到或有人知道另一种创建Windows的方法吗?我可以手动处理窗口循环吗?

欢迎任何想法。

如果有一种方法可以使用WPF窗口来实现这一点,那就太棒了。然后我可以有一个OpenGL控件和所有WPF-Stuff来制作一个编辑器!

2 个答案:

答案 0 :(得分:1)

解决方案是致电

Application.DoEvents();
有人告诉我,手动在我的渲染循环中

。所以我没有必要使用Application.Run并且能够在循环的线程中使用我的表单:

public void Run()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(true);

    IsRunning = true;
    this.Initialize();

    MyForm = new CoolRenderForm();
    MyForm.Show();

    while (IsRunning)
    {
        Render(/* arguments here */);
        Application.DoEvents();
        // refresh form
        // pausing and stuff
    }

    Dispose();
}

答案 1 :(得分:0)

根据我的问题:How to make a render loop in WPF?

WPF渲染循环

执行此操作的最佳方法是使用静态

提供的每帧回调

CompositionTarget.Rendering event.

WinForms渲染循环

下面是我基于this blog post创建的WinForms渲染循环类的代码:

只需使用:

WinFormsAppIdleHandler.Instance.ApplicationLoopDoWork += Instance_ApplicationLoopDoWork;
WinFormsAppIdleHandler.Instance.Enabled = true;

班级:

using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace Utilities.UI
{
    /// <summary>
    /// WinFormsAppIdleHandler implements a WinForms Render Loop (max FPS possible).
    /// Reference: http://blogs.msdn.com/b/tmiller/archive/2005/05/05/415008.aspx
    /// </summary>
    public sealed class WinFormsAppIdleHandler
    {
        private readonly object _completedEventLock = new object();
        private event EventHandler _applicationLoopDoWork;

        //PRIVATE Constructor
        private WinFormsAppIdleHandler()
        {
            Enabled = false;
            SleepTime = 5; //You can play/test with this value
            Application.Idle += Application_Idle;
        }

        /// <summary>
        /// Singleton from:
        /// http://csharpindepth.com/Articles/General/Singleton.aspx
        /// </summary>
        private static readonly Lazy<WinFormsAppIdleHandler> lazy = new Lazy<WinFormsAppIdleHandler>(() => new WinFormsAppIdleHandler());
        public static WinFormsAppIdleHandler Instance { get { return lazy.Value; } }

        /// <summary>
        /// Gets or sets if must fire ApplicationLoopDoWork event.
        /// </summary>
        public bool Enabled { get; set; }

        /// <summary>
        /// Gets or sets the minimum time betwen ApplicationLoopDoWork fires.
        /// </summary>
        public int SleepTime { get; set; }

        /// <summary>
        /// Fires while the UI is free to work. Sleeps for "SleepTime" ms.
        /// </summary>
        public event EventHandler ApplicationLoopDoWork
        {
            //Reason of using locks:
            //http://stackoverflow.com/questions/1037811/c-thread-safe-events
            add
            {
                lock (_completedEventLock)
                    _applicationLoopDoWork += value;
            }

            remove
            {
                lock (_completedEventLock)
                    _applicationLoopDoWork -= value;
            }
        }

        /// <summary>
        /// FINALMENTE! Imagem ao vivo sem travar! Muito bom!
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Application_Idle(object sender, EventArgs e)
        {
            //Try to update interface
            while (Enabled && IsAppStillIdle())
            {
                OnApplicationIdleDoWork(EventArgs.Empty);
                //Give a break to the processor... :)
                //8 ms -> 125 Hz
                //10 ms -> 100 Hz
                Thread.Sleep(SleepTime);
            }
        }

        private void OnApplicationIdleDoWork(EventArgs e)
        {
            var handler = _applicationLoopDoWork;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        /// <summary>
        /// Gets if the app still idle.
        /// </summary>
        /// <returns></returns>
        private static bool IsAppStillIdle()
        {
            bool stillIdle = false;
            try
            {
                Message msg;
                stillIdle = !PeekMessage(out msg, IntPtr.Zero, 0, 0, 0);
            }
            catch (Exception e)
            {
                //Should never get here... I hope...
                MessageBox.Show("IsAppStillIdle() Exception. Message: " + e.Message);
            }
            return stillIdle;
        }

        #region  Unmanaged Get PeekMessage
        // http://blogs.msdn.com/b/tmiller/archive/2005/05/05/415008.aspx
        [System.Security.SuppressUnmanagedCodeSecurity] // We won't use this maliciously
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);

        #endregion
    }
}