Getting the handle of window in C#
Asked Answered
R

3

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

Rheinlander answered 18/2, 2009 at 19:2 Comment(3)
Are we to assume that "WindowInteropHelper" is of the type System.Windows.Forms.Form?Bainbridge
From their use of WindowInteropHelper, I think it's WPF (msdn.microsoft.com/en-us/library/…)Rosalia
Not a WPF guy yet and the interface looked like the Form object. Compound that with the existing Forms answers and it's pretty confusing!Bainbridge
G
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.

Grenier answered 18/2, 2009 at 19:23 Comment(0)
T
7

The earliest place you can get the handle is OnSourceInitialized

Thundercloud answered 19/2, 2009 at 9:7 Comment(0)
C
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");
                }
Credential answered 18/2, 2009 at 19:17 Comment(1)
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.Grenier

© 2022 - 2024 — McMap. All rights reserved.