Ok, so a lot of people have asked this question in one way or another, but there doesn't seem to be many answers out there apart from pass the parent object when calling the child. The problem is, I do not have access to the parent code.
Here is my situation.
Some code I have no access to, I just have use of the dll(the parent form), calls a function in my code (the child form).
My function makes a call to a 3rd party SDK(not so important) which needs the parent form as one of the parameters. Also, I have no access to the 3rd party code, only through some c++ libraries.
Can my child form ever know its parent, or is it doomed to be an orphan?
In the most general case (since your form is somewhere in dll and you have to pass the parent form into 3rd party software) - WinAPI - you can retrieve the parent window handle with GetParent function
http://msdn.microsoft.com/en-us/library/windows/desktop/ms633510(v=vs.85).aspx
Something like that:
[DllImport("user32.dll",
EntryPoint = "GetParent",
CharSet = CharSet.Auto)]
internal static extern IntPtr GetParent(IntPtr hWnd);
...
IntPtr parentHandle = GetParent(myForm.Handle); // <- If you have a form
...
IntPtr myFormHandle = ...
IntPtr myFormParentHandle = GetParent(myFormHandle); // <- If you have WHND only
// If there's a .net form with myFormParentHandle Handle you can retrieve it
// Otherwise (e.g. form is not a .net one) you get null
Form parentForm = Control.FromHandle(myFormParentHandle) as Form;
Maybe I'm missing something, but you can just use ContainerControl.ParentForm
var parent = myForm.ParentForm;
Or (if you don't actually have a Form to interrogate, but have a Control instead):
var parent = myForm.Parent;
See http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx
Then the Windows API handle for that parent will be:
IntPtr handle = parent.Handle;
which you can pass to your 3rd party SDK.
See http://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle.aspx
If you need to check that the parent is really a Form:
Form form = myForm.Parent as Form;
if (form != null)
// Do something with form.
But like people said: You should just be able to use myForm.ParentForm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With