Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed Window from another application in our WPF window as user control?

Tags:

wpf

winapi

Is it possible to have a window from another 3rd party application shown inside our WPF Window? Preferably in a container control?

I'm guessing there might be some Win32 API that allows us to do that.

like image 592
Muhammad Hasan Khan Avatar asked Jan 05 '11 19:01

Muhammad Hasan Khan


People also ask

What is user control in WPF?

User controls, in WPF represented by the UserControl class, is the concept of grouping markup and code into a reusable container, so that the same interface, with the same functionality, can be used in several different places and even across several applications.

Can you mix Winforms and WPF?

Yes you can, both Windows Forms within a WPF application, and WPF controls within Windows Forms.

What is the difference between UserControl and window in WPF?

A window is managed by the OS and is placed on the desktop. A UserControl is managed by wpf and is placed in a Window or in another UserControl. Applcations could be created by have a single Window and displaying lots of UserControls in that Window.


1 Answers

I did that some time ago for Winforms, but the method was not to bright, so as long as anyone else doesn't have any idea, here's what I did. The code was pretty much this:

Process p = Process.Start(@"application.exe");

p.WaitForInputIdle();
IntPtr appWin = p.MainWindowHandle;

SetParent(appWin, parent);
SetWindowLong(appWin, GWL_STYLE, WS_VISIBLE);
System.Threading.Thread.Sleep(100);
MoveWindow(appWin, 0, 0, ClientRectangle.Width, ClientRectangle.Height, true);

(where SetParent, SetWindowLong and MoveWindow are the win32 API functions called via p/invoke) The sleep was needed as a hack, because without it the call to MoveWindow would have no effect.

For WPF you will need a handle to a window/control that will be the parrent of your 3rd party window and the easiest way to get such a handle is to use a HwndHost container.

I don't think there is a prettier way to achieve this in WPF. Also, note that I've only tested this in winforms, not in WPF, but it should work also in WPF, as long as it has a valid win32 HWND of the parent.

like image 63
Andrei Pana Avatar answered Oct 15 '22 11:10

Andrei Pana