繁体   English   中英

C#/Win32: WNDPROC 在被垃圾回收后被调用

[英]C#/Win32: WNDPROC is invoked after being garbage-collected

我正在使用 C# 中的 Eto.Forms 编写跨平台模拟器前端。模拟器后端需要本机 window 来显示其 output,因此,我需要编写本机控件来包装本机 windows。

要创建一个 WinAPI window,我需要创建并注册一个 window class,我喜欢这样(为清楚起见,删除了导入和 static 导入):

    static unsafe Win32SubWindow()
    {
        _refWndProc = WindowProc;

        fixed (char* pWindowClass = WINDOW_CLASS)
        {
            WNDCLASSEXW wndClass = new()
            {
                cbSize = (uint) Marshal.SizeOf<WNDCLASSEXW>(),
                style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW,
                lpfnWndProc = _refWndProc,
                cbClsExtra = 0,
                cbWndExtra = 0,
                hInstance = CurrentHInstanceRaw,
                hIcon = HICON.Null,
                hCursor = LoadCursor(HINSTANCE.Null, IDC_ARROW),
                hbrBackground = HBRUSH.Null,
                lpszMenuName = null,
                lpszClassName = pWindowClass,
                hIconSm = HICON.Null
            };

            RegisterClassEx(in wndClass);
        }
    }

    internal static readonly WNDPROC _refWndProc;

_refWndProc变量应该使委托保持活动状态直到程序结束,但是当我关闭 window 时遇到了这个错误:

Process terminated. A callback was made on a garbage collected delegate of type 'M64RPFW.Wpf!Windows.Win32.UI.WindowsAndMessaging.WNDPROC::Invoke'.
Repeat 3 times:
--------------------------------
   at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
   at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
   at MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr, Int32, IntPtr, IntPtr)
   at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
   at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
--------------------------------
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(System.Windows.Interop.MSG ByRef)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame)
   at System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(System.Object)
   at System.Windows.Application.RunInternal(System.Windows.Window)
   at System.Windows.Application.Run(System.Windows.Window)
   at Eto.Wpf.Forms.ApplicationHandler.Run()
   at Eto.Forms.Application.Run()
   at M64PRR.Wpf.Program.Main(System.String[])

什么会导致Win32SubWindow._refWndProc在仍在使用时被垃圾回收? 我发现的其他 SO 问题已通过维护对委托的引用得到解决。

该错误是由与此处提到的不同的WNDPROC实例引起的。 我的应用程序还使用助手 window 来帮助初始化 OpenGL,并将窗口的WNDPROC移动到一个变量解决了这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM