C# 检查窗口是否处于活动状态(WPF)

C# 检查窗口是否处于活动状态(WPF),c#,wpf,C#,Wpf,我想订阅类应用程序的已激活和已停用事件,但我似乎无法正确执行 我一定是做错了什么,因为它不起作用。我到处找了一些,发现了这个,对于这么简单的任务来说,它似乎太复杂了 我一直在看msdn,我最终尝试了这个,但仍然不起作用 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; u

我想订阅类应用程序的已激活和已停用事件,但我似乎无法正确执行

我一定是做错了什么,因为它不起作用。我到处找了一些,发现了这个,对于这么简单的任务来说,它似乎太复杂了

我一直在看msdn,我最终尝试了这个,但仍然不起作用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace derp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Width = 250;
            this.Height = 250;
            this.Title = "derp";

            Application app = new Application();
            app.Activated += Active;

            app.Activated += new EventHandler(Active);


        }

        void Active(object sender, EventArgs args)
        {
            //Do stuff
        }

        void Passive(object sender, EventArgs args)
        {
            //Do stuff
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
命名空间derp
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
公共主窗口()
{
初始化组件();
这个。宽度=250;
这个。高度=250;
this.Title=“derp”;
应用程序app=新应用程序();
应用程序激活+=激活;
app.Activated+=新事件处理程序(活动);
}
无效活动(对象发送方、事件args args)
{
//做事
}
无效被动(对象发送方、事件args args)
{
//做事
}
}
}

我认为这里的问题是您正在创建一个
新应用程序()
,而不是引用实际运行的当前应用程序

要获取当前运行的应用程序,请尝试改用
application.Current

请尝试:

Application app = Application.Current;

@Pethead请将他的答案标记为你问题的答案。如果对你有帮助,不要只说谢谢。谢谢@Pethead和Jaxrtech