繁体   English   中英

如何确定我的应用程序是否处于活动状态(有焦点)

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

有没有办法判断我的应用程序是否处于活动状态,即它的任何 windows has.IsActive=true?

我正在编写信使应用程序,并希望它在任务栏中的 flash 处于非活动状态且新消息到达时。

使用 P/Invoke 和循环

[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

private static bool IsActive(Window wnd)
{
    // workaround for minimization bug
    // Managed .IsActive may return wrong value
    if (wnd == null) return false;
    return GetForegroundWindow() == new WindowInteropHelper(wnd).Handle;
}

public static bool IsApplicationActive()
{
    foreach (var wnd in Application.Current.Windows.OfType<Window>())
        if (IsActive(wnd)) return true;
    return false;
}

您可以订阅主窗口的已激活事件,然后做任何您想做的事情。 你能试一试吗?

您有ApplicationActivatedDeactivated事件。

如果您希望能够绑定到IsActive ,您可以在App.xaml.cs中添加一个属性

<TextBlock Text="{Binding Path=IsActive,
                          Source={x:Static Application.Current}}"/>

当然,您也可以在代码中访问此属性,例如

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

试试这个,覆盖 MainForm 中的 OnActivated 方法并做任何你想做的事情

    protected override void OnActivated(EventArgs e)
    {
        // TODO : Implement your code here.
        base.OnActivated(e);
    }

跳这个帮助

一种方法(可能会有更多更好的方法)可以通过 Windows API 找到 Active window 然后找到 Active window API 的进程名称。

if(yourProcessName == ActiveWindowProcessName)
{
    //your window is in focus
}

另一种方法可能是保留所有 windows 的引用,当您想了解您的应用程序是否处于活动状态时,只需遍历所有 windows 并检查IsActive

另一种方法是使用 MainWindow 的OwnedWindows属性。 每当您创建新的 window 时,分配主 window 它的所有者。 然后您可以迭代 MainWindow 的所有OwnedWindows并检查是否有任何活动。(从未尝试过这种方法)

暂无
暂无

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

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