Getting the handle of window in C#


I have the following class declared:

public partial class MainWindow : Window

And I need to get the actual handle of the window once the window has one. How can I do that and where should I put the query function.

What I tried so far was:

IntPtr hwnd = new WindowInteropHelper(this).Handle;

But the handle I get back is 0, which might be because it was planted in OnInitialized - maybe the window is not ready yet at that stage. And, yes - it is connected via WPF, thank you for pointing it out!


4/16/2012 11:14:52 AM

Accepted Answer

In the OnInitialized method the handle has not yet been created. But you are on the right track. If you put your call in the Loaded event the handle will have been created and it should return the correct handle.

10/9/2012 6:29:37 PM

The earliest place you can get the handle is OnSourceInitialized

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow