Search code examples
c#wpf

After Disposing HwndSource calling close() on window leads to System.NullReferenceException


I am calling new Window1().ShowDialog(); from MainWindow when Dispose() is called on HwndSource calling this.close() on Window arise An unhandled exception of type 'System.NullReferenceException' occurred in PresentationFramework.dll Object reference not set to an instance of an object. What if i don't call Dispose, is there any problem may occurs in the future.

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
    }
}

Solution

  • DoDialogHide() seems to get upset with the dispose.

    Doing this will correct the problem

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