tags:

views:

944

answers:

4

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

+1  A: 
 [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
Mez, this works for WPF?
Henk Holterman
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
+3  A: 

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.

Stephen Martin
+1  A: 

Thank you Stephen for you answer, I'm sure it'll work.

I finally found that it was enough to catch it in the OnActivated function and so the end code looked something like:

public partial class MainWindow : Window
{
    protected override void OnActivated(EventArgs e)
    {
        WindowInteropHelper WIH = new WindowInteropHelper(this);
        IntPtr hwnd = new WindowInteropHelper(this).Handle;
       ...
    }

  ...

}

Thank you guys.

Adi
A: 

The earliest place you can get the handle is OnSourceInitialized

Nir