Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
var helper = new WindowInteropHelper(this);
var handle = helper.Handle;
var source = HwndSource.FromHwnd(handle);
When I put this piece of code in OnInitialized
override method, it returns the value 0
for handle
variable and fails in HwndSource.FromHwnd(handle)
.
But, when I put it in OnSourceInitialized
override method, it returns some random value for handle
variable and works fine in HwndSource.FromHwnd(handle)
.
I was trying to understand why is this the behavior.
What is the difference between OnInitialized and OnSourceInitialized in WPF?
–
The FrameworkElement.Initialized
event is raised when a FrameworkElement
(a WPF element) is initialized.
Here in the docs:
This event will be raised whenever the EndInit
or
OnVisualParentChanged
methods are called. Calls to either method could
have come from application code, or through the Extensible Application
Markup Language (XAML) processor behavior when a XAML page is
processed.
Than means, this event is raised when the XAML tree is processed. It can be raised for any FrameworkElement
, including a Window
.
The Window.SourceInitialized
event is raised when the underlying Win32 window handle becomes available. It is only raised on a Window
. You can read more in the HwndSource
documentation.
That is the explanation why you get a valid handle in the Window.SourceInitialized
event handler and an invalid handle (0) in the FrameworkElement.Initialized
event handler.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.