How can I refer to active Window of WPF application in C#, using something like ActiveForm property in WinForms?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With