Wpf: getting a custom control containing an HwndSource

I am writing a custom Wpf control and I need to get a link to the containing HwndSource window as soon as possible. This would be 1) in the constructor of my control, if possible, or 2) at the time the control was added to the display hierarchy.

How to determine when / if an HwndSource is available? I plan to get the link using the following code:

var source = HwndSource.FromVisual(this) as HwndSource;
+3
source share
3 answers

You can use the PresentationSource AddSourceChangedHandler method to listen when PS changes (HwndSource is a derivative of PS).

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

+4
source

, WPF . wpf hwnd.

msdn:

" WPF HWND. WPF, WPF HWND HwndSource WPF HWND. WPF HWND. , . , WPF HWND, . HwndHost HWND WPF, WPF Win32 , HWND HWND WPF."

Win32 . :

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

: :

, hwnd, WindowInteropHelper.

MSDN

#

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

vb

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

, .

+3

Window.SourceInitialized, , HWND (.. HwndSource) . , , OnVisualParentChanged. ( Window.GetWindow).

If the window has a valid HWND, you can simply use it as is. If not, you will have to subscribe to the SourceInitialized event. You can detach from SourceInitialized in your handler to make sure that it is called only once.

This will not work if your control is placed inside a Popup . In this case, you will need to get a link to the associated popup and see Opened .

+2
source

All Articles