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 inactive and new message arrives.
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
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));
}
}
}
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 can subscribe to Main Window's Activated event, and then do whatever you want. Can you give it a try?
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