private Dictionary <IntPtr, Window> GetWindows() { Dictionary <IntPtr, Window> windows = new Dictionary <IntPtr, Window>(); Stack <IntPtr> current = WinEnum.Enum(); IntPtr top = GetForegroundWindow(); while (current.Count > 0) { IntPtr hwnd = current.Pop(); windows.Add(hwnd, new Window(hwnd, top == hwnd)); } return(windows); }
private void WinWatcher(object sender, DoWorkEventArgs e) { Dictionary <IntPtr, Window> knownWindows = GetWindows(); while (!Cancel) { Thread.Sleep(100); // no cpu hogging IntPtr top = GetForegroundWindow(); Stack <IntPtr> openWindows = WinEnum.Enum(); var closed = knownWindows.Keys.Except(openWindows).ToArray(); // 3-21-15 It needs to be copied. Don't use the ExceptIterator if (OnWindowClose == null) { foreach (IntPtr hwnd in closed) { knownWindows.Remove(hwnd); } } else { foreach (IntPtr hwnd in closed) { Window win = knownWindows[hwnd]; if (!win.IsTitleEmpty()) { OnWindowClose.Invoke(win, EventArgs.Empty); } knownWindows.Remove(hwnd); } } while (openWindows.Count > 0) { IntPtr hwnd = openWindows.Pop(); Window win; if (knownWindows.TryGetValue(hwnd, out win)) { win.Update(top == hwnd); while (win.QueueCount > 0) { SysEvent sysEvent = win.Dequeue(); if (OnWindowMinimize != null && sysEvent == SysEvent.OnWindowMinimize) { OnWindowMinimize.Invoke(win, EventArgs.Empty); } if (OnWindowMaximize != null && sysEvent == SysEvent.OnWindowMaximize) { OnWindowMaximize.Invoke(win, EventArgs.Empty); } if (OnWindowTitleChange != null && sysEvent == SysEvent.OnWindowTitleChange) { OnWindowTitleChange.Invoke(win, EventArgs.Empty); } if (OnWindowFocus != null && sysEvent == SysEvent.OnWindowFocus) { OnWindowFocus.Invoke(win, EventArgs.Empty); } if (OnWindowNoFocus != null && sysEvent == SysEvent.OnWindowNoFocus) { OnWindowNoFocus.Invoke(win, EventArgs.Empty); } if (OnWindowHide != null && sysEvent == SysEvent.OnWindowHide) { OnWindowHide.Invoke(win, EventArgs.Empty); } if (OnWindowShow != null && sysEvent == SysEvent.OnWindowShow) { OnWindowShow.Invoke(win, EventArgs.Empty); } } } else { win = new Window(hwnd, top == hwnd); if (OnWindowOpen != null && !win.IsTitleEmpty()) { OnWindowOpen.Invoke(win, EventArgs.Empty); } knownWindows.Add(hwnd, win); } } } e.Cancel = true; }