Is there a way to tell whether my application is active i.e. any of its windows has .IsActive=true?
I\'m writing messenger app and want it to flash in taskbar when it is
try this, override OnActivated method in your MainForm and do whatever you want
protected override void OnActivated(EventArgs e)
{
// TODO : Implement your code here.
base.OnActivated(e);
}
hop this help
One way (may be there would be more better ways) can be to find the Active window through Windows API then find the process name of active window.
if(yourProcessName == ActiveWindowProcessName)
{
//your window is in focus
}
Another way could be to keep a reference of all the windows and when you want to find out whether your app is active or not just iterate through all the windows and check IsActive
value
Another way could be to use OwnedWindows
property of MainWindow. Whenever you are creating a new window assign main window it's owner. Then you can iterate all the OwnedWindows
of MainWindow and check whether any is active or not.(never tried this approach)
Used P/Invoke and loop
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
private static bool IsActive(Window wnd)
{
// workaround for minimization bug
// Managed .IsActive may return wrong value
if (wnd == null) return false;
return GetForegroundWindow() == new WindowInteropHelper(wnd).Handle;
}
public static bool IsApplicationActive()
{
foreach (var wnd in Application.Current.Windows.OfType<Window>())
if (IsActive(wnd)) return true;
return false;
}
You have the Activated
and Deactivated
events of Application
.
If you want to be able to Bind to IsActive
you can add a Property in App.xaml.cs
<TextBlock Text="{Binding Path=IsActive,
Source={x:Static Application.Current}}"/>
of course you can also access this property in code like
App application = Application.Current as App;
bool isActive = application.IsActive;
App.xaml.cs
public partial class App : Application, INotifyPropertyChanged
{
private bool m_isActive;
public bool IsActive
{
get { return m_isActive; }
private set
{
m_isActive = value;
OnPropertyChanged("IsActive");
}
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Activated += (object sender, EventArgs ea) =>
{
IsActive = true;
};
Deactivated += (object sender, EventArgs ea) =>
{
IsActive = false;
};
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
You can subscribe to Main Window's Activated event, and then do whatever you want. Can you give it a try?