获取所有打开的 WPF 窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12177133/
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-09-13 05:08:35  来源:igfitidea点击:

Get all open WPF windows

c#wpfwindows

提问by Mister S

I'm trying to get all open windows. I tried to use System.Windows.Application.Current.Windowsbut I get Null Pointer Exception in line where foreachloop is. Do anyone has idea what is wrong?

我正在尝试打开所有打开的窗口。我尝试使用,System.Windows.Application.Current.Windows但在foreach循环所在的行中出现空指针异常。有谁知道出了什么问题?

public Window getWindow(String Title)
{
    Window windowObject = null;
    Console.WriteLine("Inside getWindow");
    foreach (Window window in System.Windows.Application.Current.Windows)
    {
        if (window.Title == Title)
        {
            windowObject = window;
        }
    }
    return windowObject;
}

回答by luka

This is how you cycle through all opened windows in an running application in WPF:

这是您在 WPF 中运行的应用程序中循环浏览所有打开的窗口的方式:

foreach (var Window in App.Current.Windows)
        { 
           // TODO: write what you want here
        }

If you want know in windowforms use application instead of app. bye.

如果您想在 windowforms 中使用应用程序而不是应用程序。再见。

回答by Erno

Either Currentor Windowsis null

无论是CurrentWindowsISnull

The Windows propertycan only be access from the thread that created the Application object and this will only work in a WPF application AFTER the application object has been created.

Windows属性只能从创建Application对象的线程访问,这将只在WPF应用程序的应用对象后,工作已创建。

回答by Rasive

Bare in mind that System.Windows is a namespace, and Application is the actual class that referencesthe current application context. What this means is that ′Application.Current.Windows′ only references all windows spawned by the application itself. Try to loop through all windows and print their title.

请记住 System.Windows 是一个命名空间,而 Application 是引用当前应用程序上下文的实际类。这意味着“Application.Current.Windows”只引用应用程序本身产生的所有窗口。尝试遍历所有窗口并打印它们的标题。

What happens in your program, is that the if statement will always be false, unless Title is equal to a window spawned by the Application, thus windowObject will remain to be null, and null will be returned by the method.

在您的程序中发生的情况是,if 语句将始终为假,除非 Title 等于应用程序生成的窗口,因此 windowObject 将保持为 null,并且该方法将返回 null。