Ejemplo n.º 1
0
        public static IntPtr FindProcessWindow(string processName)
        {
            var hwndFound = IntPtr.Zero;

            bool enumWindowsProc(IntPtr hwnd, IntPtr lparam)
            {
                if (!WinApi.IsWindowVisible(hwnd))
                {
                    return(true);
                }

                WinApi.GetWindowThreadProcessId(hwnd, out var pid);
                if (pid == 0)
                {
                    return(true);
                }

                var hProcess = WinApi.OpenProcess(WinApi.PROCESS_QUERY_LIMITED_INFORMATION, false, pid);

                if (hProcess == IntPtr.Zero)
                {
                    return(true);
                }
                try
                {
                    var buffer = new StringBuilder(1024);
                    int size   = buffer.Capacity;
                    if (WinApi.QueryFullProcessImageName(hProcess, 0, buffer, out size))
                    {
                        var path     = buffer.ToString();
                        var fileName = System.IO.Path.GetFileNameWithoutExtension(path);
                        if (String.Compare(fileName, processName, ignoreCase: true) == 0)
                        {
                            hwndFound = hwnd;
                            return(false);
                        }
                    }
                }
                finally
                {
                    WinApi.CloseHandle(hProcess);
                }
                return(true);
            }

            WinApi.EnumDesktopWindows(IntPtr.Zero, enumWindowsProc, IntPtr.Zero);
            return(hwndFound);
        }
Ejemplo n.º 2
0
        public static IntPtr GetPrevActiveWindow()
        {
            var foregroundWindow = WinApi.GetAncestor(WinApi.GetForegroundWindow(), WinApi.GA_ROOT);

            var hwndPrev  = IntPtr.Zero;
            var hwndFound = IntPtr.Zero;

            bool enumWindowsProc(IntPtr hwnd, IntPtr lparam)
            {
                if (WinApi.IsWindowVisible(hwnd))
                {
                    if (hwndPrev == foregroundWindow)
                    {
                        hwndFound = hwnd;
                        return(false);
                    }
                    hwndPrev = hwnd;
                }
                return(true);
            }

            WinApi.EnumDesktopWindows(IntPtr.Zero, enumWindowsProc, IntPtr.Zero);
            return(hwndFound);
        }