示例#1
0
        public static IntPtr GetFocusedHandle(uint threadId, WindowSelectorEventArgs e = null) //Получение хендла активного контрола
        {
            //@kurumpa http://stackoverflow.com/a/28409126
            IntPtr hWnd          = IntPtr.Zero;
            IntPtr focusedHandle = IntPtr.Zero;
            var    info          = new WinApi.GUITHREADINFO();

            info.cbSize = Marshal.SizeOf(info);
            var success = WinApi.GetGUIThreadInfo(threadId, ref info);

            // target = hwndCaret || hwndFocus || (AttachThreadInput + GetFocus) || hwndActive
            var currentThreadId = WinApi.GetCurrentThreadId();

            if (currentThreadId != threadId)
            {
                WinApi.AttachThreadInput(threadId, currentThreadId, true);
            }
            focusedHandle = WinApi.GetFocus();
            if (e != null)
            {
                e.HGetActiveWindow = (int)WinApi.GetActiveWindow();
            }
            if (currentThreadId != threadId)
            {
                WinApi.AttachThreadInput(threadId, currentThreadId, false);
            }
            if (e != null)
            {
                e.HGetFocus = (int)focusedHandle;
                if (success)
                {
                    e.HCaret   = (int)info.hwndCaret;
                    e.HFocus   = (int)info.hwndFocus;
                    e.HActive  = (int)info.hwndActive;
                    e.HCapture = (int)info.hwndCapture;
                }
            }
            if (success)
            {
                if (info.hwndCaret != IntPtr.Zero)
                {
                    hWnd = info.hwndCaret;
                }
                else if (info.hwndFocus != IntPtr.Zero)
                {
                    hWnd = info.hwndFocus;
                }
                else if (focusedHandle != IntPtr.Zero)
                {
                    hWnd = focusedHandle;
                }
                else if (info.hwndActive != IntPtr.Zero)
                {
                    hWnd = info.hwndActive;
                }
            }
            else
            {
                hWnd = focusedHandle;
            }
            return(hWnd);
        }