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

4

我想订阅 Application 类的激活和取消激活事件,但似乎做错了什么。

一定是我做错了什么,因为它不起作用。我搜索了一些内容,找到了这个链接: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个回答

4

我认为问题在于你创建了一个new Application(),而没有引用实际正在运行的当前应用程序。

尝试使用Application.Current来获取当前正在运行的应用程序。 [MSDN 参考]

请尝试改为:

Application app = Application.Current;

1
@Pethead请将他(Jaxrtech)的回答标记为您问题的答案。如果对您有帮助,请不要只是说谢谢。 - Eriawan Kusumawardhono
很好,感谢 @Pethead 和 Jaxrtech。 - Saxophonist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接