Does holding the windows handle (IntPtr) in a variable prevent the form from being properly disposed?

StackOverflow https://stackoverflow.com/questions/13472049

  •  30-11-2021
  •  | 
  •  

Question

I have a class that needs to perform specific actions. Based on the input data, some dialogs might be shown. These dialogs need to be invoked with the parent window's handle so that they're centered correctly etc.

private IntPtr _parentWindow;
...
System.Windows.Forms.MessageBox.Show(System.Windows.Forms.Control.FromHandle(_parentWindow), "message");

After the parent form is ultimately closed, my class's instance still exists, with _parentWindow still assigned with a value.

Is this safe to do? Or would the GC not fully dispose the form on account of _parentWindow being populated with the handle?

Was it helpful?

Solution

No, keeping the value of the window handle around won't keep the window from being destroyed or its resources from being fully released.

The GC is not responsible for releasing the unmanaged resources of the form (said resources being the window handle; this is ultimately released through DestroyWindow), and neither does it treat IntPtr members in a special manner.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top