簡體   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