【问题标题】:After Disposing HwndSource calling close() on window leads to System.NullReferenceException在窗口上处理 HwndSource 调用 close() 后导致 System.NullReferenceException
【发布时间】:2022-11-27 05:06:47
【问题描述】:

当在 HwndSource 上调用 Dispose() 在 Window 上调用 this.close() 时,我从 MainWindow 调用 new Window1().ShowDialog(); An unhandled exception of type 'System.NullReferenceException' occurred in PresentationFramework.dll Object reference not set to an instance of an object. 如果我不调用Dispose怎么办,将来会不会有什么问题。

public partial class Window1 : Window
{
    private const int MESSAGE_CAPTURED_OK = 0x0400 + 6;
    private HwndSource source;

    public Window1()
    {
        InitializeComponent();
        Closing += Window_Closing;
    }
    private void Close_Click(object sender, RoutedEventArgs e) => this.Close();

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);

        var FormHandle = new WindowInteropHelper(this).Handle;
        source = HwndSource.FromHwnd(FormHandle);
        source.AddHook(WndProc);
    }

    IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        // Handle messages...
        if (msg == MESSAGE_CAPTURED_OK)
        {
            // operations
        }
        return IntPtr.Zero;
    }

    private void Window_Closing(object sender, CancelEventArgs e)
    {
        source.RemoveHook(WndProc);
        //source.Dispose(); This line rises error
    }
}

【问题讨论】:

  • 是 WPF 还是 WinUI?你不应该混合标签
  • 它是 WPF,我删除了 WinUI 标签。

标签: c# wpf


【解决方案1】:

DoDialogHide() 似乎对处置感到不安。

这样做可以解决问题

private void Window_Closing(object sender, CancelEventArgs e)
{
    Hide();
    source.RemoveHook(WndProc);
    source.Dispose();
}

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2014-05-29
    • 2012-09-29
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多