简体   繁体   English

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

[英]Check if window is active or not WPF

I want to subscribe to the Activated and Deactivated events of the class Application but I can't seem to get it right. 我想订阅类Application的Activated和Deactivated事件,但我似乎无法做到正确。

I must be doing something wrong cause It's not working I searched around some and found this http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/ and it just seems way too complicated for such an easy task. 我一定做错了因为它不工作我搜索了一些并发现了这个http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in -c /对于这么简单的任务来说,这似乎太复杂了。

I've been looking around in msdn and I eventually tried this http://msdn.microsoft.com/en-us/library/ms366768.aspx but still not working... 我一直在寻找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
        }
    }
}

I think the issue here is that you are creating a new Application() and not referencing the actual current one running. 我认为这里的问题是你正在创建一个new Application()而不是引用当前运行的实际new Application()

To get the currently running application try using Application.Current instead. 要获取当前运行的应用程序,请尝试使用Application.Current [MSDN Ref] [MSDN参考]

Try instead: 尝试改为:

Application app = Application.Current;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM