简体   繁体   English

获取所有打开的 WPF 窗口

[英]Get all open WPF windows

I'm trying to get all open windows.我正在尝试打开所有打开的窗口。 I tried to use System.Windows.Application.Current.Windows but I get Null Pointer Exception in line where foreach loop is.我尝试使用System.Windows.Application.Current.Windows但我在foreach循环所在的行中得到空指针异常。 Do anyone has idea what is wrong?有谁知道出了什么问题?

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

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.如果您想在 windowforms 中知道使用应用程序而不是应用程序。 bye.再见。

Either Current or Windows is null CurrentWindowsnull

The Windows property can 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 应用程序中工作。

Bare in mind that System.Windows is a namespace, and Application is the actual class that references the current application context.请记住 System.Windows 是一个命名空间,而 Application 是引用当前应用程序上下文的实际类。 What this means is that ´Application.Current.Windows´ only references all windows spawned by the application itself.这意味着“Application.Current.Windows”只引用应用程序本身产生的所有窗口。 Try to loop through all windows and print their title.尝试遍历所有窗口并打印它们的标题。

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM