private AttachedThreadInputScope()
        {
            s_current.Value?.Dispose();
            s_current.Value = this;

            _foregroundWindow   = WinApi.GetForegroundWindow();
            _currentThreadId    = WinApi.GetCurrentThreadId();
            _foregroundThreadId = WinApi.GetWindowThreadProcessId(_foregroundWindow, out var _);

            if (_currentThreadId != _foregroundThreadId)
            {
                // attach to the foreground thread
                if (!WinApi.AttachThreadInput(_currentThreadId, _foregroundThreadId, true))
                {
                    // unable to attach, see if the window is a Win10 Console Window
                    var className = new StringBuilder(capacity: 256);
                    WinApi.GetClassName(_foregroundWindow, className, className.Capacity - 1);
                    if (String.CompareOrdinal("ConsoleWindowClass", className.ToString()) != 0)
                    {
                        return;
                    }
                    // consider attached to a console window
                }
            }

            _attached = true;
        }
Beispiel #2
0
        public static bool TryGetThirdPartyForgroundWindow(out IntPtr hwnd)
        {
            hwnd = IntPtr.Zero;
            var foregroundWindow = WinApi.GetForegroundWindow();
            var currentThreadId  = WinApi.GetCurrentThreadId();
            var foregroundThread = WinApi.GetWindowThreadProcessId(foregroundWindow, out var _);

            if (currentThreadId == foregroundThread)
            {
                return(false);
            }
            else
            {
                var hwndRoot = WinApi.GetAncestor(foregroundWindow, WinApi.GA_ROOT);
                if (hwndRoot != IntPtr.Zero)
                {
                    foregroundWindow = hwndRoot;
                }

                var className = new StringBuilder(capacity: 256);
                WinApi.GetClassName(foregroundWindow, className, className.Capacity - 1);
                if (className.ToString().CompareTo("Shell_TrayWnd") == 0)
                {
                    return(false);
                }

                hwnd = foregroundWindow;
                return(true);
            }
        }