Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether my application is active (has focus)

Tags:

c#

.net

wpf

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.

like image 539
Poma Avatar asked Aug 13 '11 10:08

Poma


4 Answers

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

like image 77
saber Avatar answered Nov 06 '22 18:11

saber


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));
        }
    }
}
like image 32
Fredrik Hedblad Avatar answered Oct 13 '22 10:10

Fredrik Hedblad


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;
}
like image 11
Poma Avatar answered Nov 06 '22 18:11

Poma


You can subscribe to Main Window's Activated event, and then do whatever you want. Can you give it a try?

like image 8
sll Avatar answered Nov 06 '22 18:11

sll