在C#中获取窗口句柄

24

我声明了以下类:

public partial class MainWindow : Window

当窗口有一个句柄时,我需要获取窗口的实际句柄。我应该如何做,查询函数应该放在哪里。

我尝试过的方法是:

IntPtr hwnd = new WindowInteropHelper(this).Handle;

但是我得到的句柄是0,这可能是因为它被放置在OnInitialized中 - 可能在那个阶段窗口尚未准备好。 而且,是的 - 它通过WPF连接,感谢你指出!

谢谢


我们应该假设"WindowInteropHelper"是类型为System.Windows.Forms.Form吗? - Austin Salonen
从他们使用WindowInteropHelper来看,我认为这是WPF(http://msdn.microsoft.com/en-us/library/system.windows.interop.windowinterophelper.aspx)。 - Daniel LeCheminant
还不是一个WPF的人,界面看起来像Form对象。再加上现有的Forms答案,就相当令人困惑! - Austin Salonen
3个回答

26
OnInitialized 方法中,handle 还没有被创建。但是你走在了正确的轨迹上。如果将调用放在 Loaded 事件中,handle 就已经被创建,并且它应该返回正确的 handle

7
最早可以获取句柄的位置是在OnSourceInitialized事件中。

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");
                }

3
在原帖中,发帖者试图在句柄被创建之前检索它,因此这种方法也总是失败的。大多数int参数应该是IntPtr,在64位平台上将会失败得非常惨。最后,这仅会搜索顶级窗口。 - Stephen Martin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接