相关文章推荐
完美的馒头  ·  python QTreeWidget ...·  1 月前    · 
聪明的冰棍  ·  can't access source ...·  3 周前    · 
开朗的眼镜  ·  ue4版本不同打不开-掘金·  1 年前    · 
文雅的炒饭  ·  await Vue.nextTick() ...·  1 年前    · 
眼睛小的鞭炮  ·  北京航空航天大学·  1 年前    · 
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?

Here is a question about source initialiazed. The answer contains interesting links to this: stackoverflow.com/questions/12077707/… – Malior Feb 12, 2019 at 8:55

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.