检查窗口是否处于活动状态WPF

时间:2014-01-16 01:31:20

标签: c# wpf

我想订阅类Application的Activated和Deactivated事件,但我似乎无法做到正确。

我必须做错事因为它没有工作我搜索了一些并发现了这个http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/而且这对于这么简单的任务来说似乎太复杂了。

我一直在寻找msdn,我最终尝试了http://msdn.microsoft.com/en-us/library/ms366768.aspx,但仍然没有工作......

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

1 个答案:

答案 0 :(得分:4)

我认为这里的问题是你正在创建一个new Application()而没有引用当前正在运行的实际值。

要获取当前正在运行的应用程序,请尝试使用Application.Current[MSDN Ref]

尝试改为:

Application app = Application.Current;