/// <summary> /// 根据句柄获取子句柄列表 /// </summary> /// <param name="hwndParent">句柄</param> /// <returns>子句柄列表</returns> public static List <IntPtr> GetChildWindows(IntPtr hwndParent) { var childHandles = new List <IntPtr>(); var gcChildhandles = GCHandle.Alloc(childHandles); try { var callback = new Win32Api.EnumWindowDelegate((hWnd, lParam) => { var gcChandles = GCHandle.FromIntPtr(lParam); // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (gcChandles == null || gcChandles.Target == null) { return(false); } var cHandles = gcChandles.Target as List <IntPtr>; cHandles?.Add(hWnd); return(true); }); Win32Api.EnumChildWindows(hwndParent, callback, GCHandle.ToIntPtr(gcChildhandles)); } finally { if (gcChildhandles.IsAllocated) { gcChildhandles.Free(); } } return(childHandles.Distinct().ToList()); }
public Task UpdateWindows() { if (_UpdateWindowsTask != null) { return(_UpdateWindowsTask); } _UpdateWindowsTask = Task.Run(() => { var newWindows = new List <WindowData>(); Action <IntPtr> addWindow = windowHandle => { var windowTitle = Win32Api.GetWindowTitle(windowHandle); var windowIcon = GetWindowIcon(windowHandle); windowIcon?.Freeze(); var flashing = GetFlashingWindowState(windowHandle); newWindows.Add(new WindowData(windowHandle, windowIcon, windowTitle, flashing)); if (!_UsageHistory.ContainsKey(windowTitle.ToLower())) { _UsageHistory[windowTitle.ToLower()] = 0; } }; Win32Api.EnumWindowDelegate enumWindowCallback = (windowHandle, lParam) => { try { if (IsAllowedWindow(windowHandle)) { var currentProcessId = Win32Api.GetWindowProcessId(windowHandle); var windowTitle = Win32Api.GetWindowTitle(windowHandle); if (Process.GetCurrentProcess().Id != currentProcessId && !String.IsNullOrWhiteSpace(windowTitle)) { addWindow(windowHandle); } } } catch { } return(true); }; Win32Api.EnumDesktopWindows(IntPtr.Zero, enumWindowCallback, IntPtr.Zero); Common.RunFromSTAThread(() => { Windows = SortWindows(newWindows.Select(window => new WindowDataViewModel(window)).ToList()); _UpdateWindowsTask = null; }); }); return(_UpdateWindowsTask); }