Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wpf: Getting the containing HwndSource of a custom control

Tags:

.net

wpf

hwnd

I'm writing a custom Wpf control and I need to grab a reference to the containing window's HwndSource at the earliest possible time. This would be 1) in the constructor of my control if possible or 2) at the point when the control is added to the display hierarchy.

How can I detect when/if the HwndSource is available? I plan to acquire a reference using code such as the following:

var source = HwndSource.FromVisual(this) as HwndSource;
like image 946
anthony Avatar asked Jan 31 '26 11:01

anthony


2 Answers

You can use the PresentationSource's AddSourceChangedHandler method to listen for when the PS changes (HwndSource is a derived PS).

http://msdn.microsoft.com/en-us/library/system.windows.presentationsource.addsourcechangedhandler.aspx

like image 122
AndrewS Avatar answered Feb 03 '26 06:02

AndrewS


As far as I understand, WPF controls are not windows. Only the window in a wpf app has a hwnd.

From the msdn site:

"All WPF elements on the screen are ultimately backed by a HWND. When you create a WPF Window, WPF creates a top-level HWND, and uses an HwndSource to put the Window and its WPF content inside the HWND. The rest of your WPF content in the application shares that singular HWND. An exception is menus, combo box drop downs, and other pop-ups. These elements create their own top-level window, which is why a WPF menu can potentially go past the edge of the window HWND that contains it. When you use HwndHost to put an HWND inside WPF, WPF informs Win32 how to position the new child HWND relative to the WPF Window HWND."

For Win32 interoperability see the following link:

http://msdn.microsoft.com/en-us/library/ms742522.aspx

Edit: To enhance the answer to address the comment below:

In order to get the handle of the window that owns the hwnd, you can use the WindowInteropHelper class.

This example is also pulled from the MSDN documentation

in c#

WindowInteropHelper wih = new WindowInteropHelper(myDialog);
wih.Owner = ownerHwnd;
myDialog.ShowDialog();

in vb

Dim wih As New WindowInteropHelper(myDialog)
wih.Owner = ownerHwnd
myDialog.ShowDialog()

I hope this helps.

like image 23
Rendition Avatar answered Feb 03 '26 06:02

Rendition