如何确定我的应用程序是否处于活动状态(具有焦点)
有没有办法判断我的应用程序是否处于活动状态,即它的任何窗口都有.IsActive = true?
我正在编写Messenger应用程序并希望它在任务栏中闪烁,当它处于非活动状态并且新消息到达时。
使用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()) if (IsActive(wnd)) return true; return false; }
您可以订阅主窗口的已激活事件,然后执行任何操作。 你能试一试吗?
试试这个,在你的MainForm中覆盖OnActivated方法并做你想做的任何事情
protected override void OnActivated(EventArgs e) { // TODO : Implement your code here. base.OnActivated(e); }
跳这个帮助
您有Application
已Activated
和Deactivated
事件。
如果您希望能够绑定到IsActive
,可以在App.xaml.cs
添加一个属性
当然,您也可以使用代码访问此属性
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)); } } }
一种方法(可能会有更好的方法)可以通过Windows API找到Active窗口,然后找到活动窗口的进程名称。
if(yourProcessName == ActiveWindowProcessName) { //your window is in focus }
另一种方法是保持所有窗口的引用,当你想知道你的应用程序是否处于活动状态时,只需迭代所有窗口并检查IsActive
值
另一种方法是使用MainWindow的OwnedWindows
属性。 无论何时创建新窗口,都指定主窗口为其所有者。 然后你可以迭代MainWindow的所有OwnedWindows
并检查是否有任何活动。(从未尝试过这种方法)