Refer to active Window in WPF? Refer to active Window in WPF? wpf wpf

Refer to active Window in WPF?


One possible way would be to scan the list of open windows in the application and check which one of them has IsActive = true:

Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);

Not sure if there may be more than one active window if, for example, there's a modal dialog showing, in which case, the owner of the dialog and the dialog itself might be active.


There is better way to do this using PInvoke. Aviads answer is not working all the time (there are some edge cases with dialogs).

IntPtr active = GetActiveWindow();ActiveWindow = Application.Current.Windows.OfType<Window>()    .SingleOrDefault(window => new WindowInteropHelper(window).Handle == active);

One must include following import first:

[DllImport("user32.dll")]static extern IntPtr GetActiveWindow();


I know this is a bit old question but I think my answer could help someone.

My problem was this: I had a WPF MVVM application and I needed to get my MainWindow instance in the second view, i.e. second view model, in order to set the visibility of title bar button to visible.

This is my solution:

MainWindow window = (MyApp.MainWindow)App.Current.MainWindow;window.btnSearch.Visibility = System.Windows.Visibility.Visible;

Hope this would help someone.