【发布时间】: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 标签。