Wpf: Why only after window.show() beem called, then we can get the handle of the window?

Created on 10 Jul 2020  路  7Comments  路  Source: dotnet/wpf

I wanna get the handle of a window, but i found that only after i called window.show(), then the handle is not null. I understand this is a lazy load strategy, but is there a way that once i create a new window instance, i can get the handle immediately. If not, do wpf will support in the future?

Thank you!

Most helpful comment

Use WindowInteropHelper.EnsureHandle().

All 7 comments

What's the use case for this?

What's the use case for this?

See this:

Window wnd = new Window();
var wndInteropHelper = new WindowInteropHelper(wnd );
var handle = window.Handle. // The handle is IntPtr.Zero. But I wanna use the handle now and don't wanna show wnd.

wnd.Show();
handle = window.Handle. // After show() called, the handle is a real handle value.

Thx for replying!

I get what you want, but i don't understand in which case this would be useful/needed.

Use WindowInteropHelper.EnsureHandle().

Use WindowInteropHelper.EnsureHandle().

Thx! This is the answser!

You can also subscribe to Window.SourceInitialized which in my experience gets called the moment the handle is created.

@batzen I don't know what the OP had in mind, but here's an example: I needed to use EnsureHandle in one case where I was setting an attached property on the window itself; at the time the value of the AP was being set, the window wasn't yet loaded, but the AP needed the Hwnd to do its job.

Was this page helpful?
0 / 5 - 0 ratings