Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between OnInitialized and OnSourceInitialized in WPF

Tags:

c#

wpf

I was trying to add global hotkeys in WPF.

        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?

like image 676
Alen Alex Avatar asked Sep 08 '26 10:09

Alen Alex


1 Answers

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.

like image 100
dymanoid Avatar answered Sep 10 '26 23:09

dymanoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!