10

我正在尝试打开所有打开的窗口。我尝试使用,但在循环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;
}
4

3 回答 3

11

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

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

如果您想知道在窗口窗体中使用应用程序而不是应用程序。再见。

于 2016-06-22T05:54:38.823 回答
4

要么Current要么Windowsnull

Windows 属性只能从创建应用程序对象的线程访问,并且这仅在创建应用程序对象后的 WPF 应用程序中有效。

于 2012-08-29T11:48:06.400 回答
1

Bare in mind that System.Windows is a namespace, and Application is the actual class that references the 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.

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.

于 2014-06-08T16:13:00.747 回答