处理HwndSource后,在窗口上调用close()导致System.NullReferenceException.&



当在HwndSource上调用this.close()在Window ariseAn unhandled exception of type 'System.NullReferenceException' occurred in PresentationFramework.dll Object reference not set to an instance of an object.上调用Dispose()时,从MainWindow调用new Window1().ShowDialog();如果我不调用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
}
}

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

这样做将纠正问题

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

相关内容

最新更新