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

前端 未结 5 1278
天命终不由人
天命终不由人 2021-02-05 18:53

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

5条回答
  •  你的背包
    2021-02-05 19:35

    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

    
    

    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));
            }
        }
    }
    

提交回复
热议问题