Host a process window inside your applications window
The following snippet will allow you to host the window of any application inside your own application. This isn’t a recommended practice but it’s a fun method that might spawn some interesting ideas.
In order to get this working we will need to pinvoke two Win32 functions, SetParent
and SetWindowPos
.
Place the following lines in your class
1 2 3 4 | [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); [DllImport("user32.dll", EntryPoint = "SetWindowPos")] public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags); |
Now add our LoadApplication method which takes a string and an IntPtr value as an argument and will attempt to run the application and set our argument handle value as its parent.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | private void LoadApplication(string path, IntPtr handle) { Stopwatch sw = new Stopwatch(); sw.Start(); int timeout = 10 * 1000; // Timeout value (10s) in case we want to cancel the task if it's taking too long. Process p = Process.Start(path); while (p.MainWindowHandle == IntPtr.Zero) { System.Threading.Thread.Sleep(10); p.Refresh(); if (sw.ElapsedMilliseconds > timeout) { sw.Stop(); return; } } SetParent(p.MainWindowHandle, handle); // Set the process parent window to the window we want SetWindowPos(p.MainWindowHandle, 0, 0, 0, 0, 0, 0x0001 | 0x0040); // Place the window in the top left of the parent window without resizing it } |
And we are done! Now just call our LoadApplication method with the file you want its window to be in your application
1 2 3 | LoadApplication(@"c:\windows\system32\notepad.exe", this.Handle); LoadApplication(@"c:\windows\system32\calc", this.Handle); LoadApplication(@"c:\windows\system32\calc", this.Handle); |
I have developed an app using MS Word (VSTO Addin) and has a child windows form inside the app. first MS Word Application gets launched and then the form. I want to set MS Word inside this form. I tried the same method as you mentioned but it did not worked.
I do not want to create a windows form as a separate application and also cannot change the loading sequence in my App.
Kindly help
Is there a way to do this while limiting the application within a grid or stackpanel? I’d like the external application to be docked within a grid I have on a specific tab in my application.
How do you reverse this now? I am able to do the above but now need to be able to reverse it.
@mike, simply put a null parent with setParent