24

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!

Thanks

Steve Greatrex
  • 15,789
  • 5
  • 59
  • 73
Adi
  • 2,033
  • 5
  • 23
  • 26

3 Answers3

26

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.

SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173
Stephen Martin
  • 9,495
  • 3
  • 26
  • 36
7

The earliest place you can get the handle is OnSourceInitialized

Nir
  • 29,306
  • 10
  • 67
  • 103
0
 [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        public static extern int FindWindowEx(int hwndParent, int hwndEnfant, int lpClasse, string lpTitre);


int hwnd = FindWindowEx(0, 0, 0, title);//where title is the windowtitle

                //verification of the window
                if (hwnd == 0)
                {
                    throw new Exception("Window not found");
                }
Mez
  • 2,817
  • 4
  • 27
  • 29
  • 3
    In the original post the poster is trying to retrieve the handle before it is created, so this method will also always fail. Most of the int parameters should be IntPtr, on a 64 bit platform this will fail spectacularly. Finally, this will only search top-level windows. – Stephen Martin Feb 18 '09 at 20:35