在 C# 中获取窗口句柄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/562392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:16:37  来源:igfitidea点击:

Getting the handle of window in C#

c#wpfwindows

提问by Adi

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!

但是我返回的句柄是 0,这可能是因为它是在 OnInitialized 中植入的——也许在那个阶段窗口还没有准备好。而且,是的 - 它是通过 WPF 连接的,感谢您指出!

Thanks

谢谢

采纳答案by Stephen Martin

In the OnInitializedmethod the handlehas not yet been created. But you are on the right track. If you put your call in the Loadedevent the handlewill have been created and it should return the correct handle.

在该OnInitialized方法中,尚未创建句柄。但你走在正确的轨道上。如果你把你的调用放在Loaded事件中,句柄将被创建,它应该返回正确的句柄

回答by Mez

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

回答by Nir

The earliest place you can get the handle is OnSourceInitialized

最早可以拿到句柄的地方是 OnSourceInitialized