Mister S
Mister S

Reputation: 213

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

Upvotes: 11

Views: 23332

Answers (3)

luka
luka

Reputation: 637

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

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

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

Upvotes: 12

Rasive
Rasive

Reputation: 1143

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.

Upvotes: 0

Emond
Emond

Reputation: 50672

Either Current or Windows is null

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.

Upvotes: 4

Related Questions