In interfacing some new .NET code to a legacy c++ application, I would find it very convenient to be able to convert the Process "Handle" to a proper Windows SDK HWND so I can make my .NET forms proper child windows of my legacy app. Anybody out there know how to do this?
using System.Runtime.InteropServices;
[DllImport("User32.dll")]
private static extern int SetParent(IntPtr hwndChild, IntPtr hwndParent);
void SetMyParent (IntPtr parentHwnd) {
Process p = System.Diagnostics.Process.GetCurrentProcess();
SetParent(p.Handle, parentHwnd);
}
I've tried several variations on this theme, all to no avail. I can make this work by using the User32.dll function to GetForegroundWindow()
rather than p.Handle
, but I can't guarantee that the window I launch will always be on top. I've managed to end up with Microsoft Outlook as my child window by trying that.
I don't understand why p.Handle
isn't identical to an old fashioned HWND, and even if it isn't, why there isn't an easy conversion between the two types somewhere in InteropServices.
Thanks for any help on this!
Note: Thanks Chris, for your post (below). Granted, I have confused "process" with "window" here, but the legacy Windows SDK works almost exclusively with window handles, so if a single process has multiple windows, that still begs the question of how to enumerate them in .NET without resorting to FindWindow or EnumWindows. The problem with FindWindow is that it demands a class name, and when I examine .NET window class names, they seem to be constructed at runtime to be unique, but have little relation to the actual form class name. I'll look at the details of the link you gave to see if that provides a usable workaround for this .NET shortcoming. :thumbsup:
Comment: Thanks also to Eddy, which I've marked as the Answer. Getting lazy with code-completion led me to not see the .MainWindowHandle member of process, which is the HWND I need. Also, interesting to note that for a form, the "this" pointer has a Handle member which is the form's HWND.