Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to active Window in WPF?

Tags:

c#

window

wpf

How can I refer to active Window of WPF application in C#, using something like ActiveForm property in WinForms?

like image 413
pkain Avatar asked Jan 10 '10 22:01

pkain


2 Answers

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.

like image 170
Aviad P. Avatar answered Sep 20 '22 14:09

Aviad P.


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(); 
like image 34
ghord Avatar answered Sep 19 '22 14:09

ghord