|
| 1 | +using System; |
| 2 | +using System.Runtime.InteropServices; |
| 3 | + |
| 4 | +namespace KeyLayoutAutoSwitch |
| 5 | +{ |
| 6 | + /// <summary> |
| 7 | + /// Handles accessibility events as if a screen reader were running. Chrome detects this to automatically enable accessibility features. |
| 8 | + /// </summary> |
| 9 | + internal class ChromeAccessibilityWinEventHook : IDisposable |
| 10 | + { |
| 11 | + private delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime); |
| 12 | + |
| 13 | + [DllImport("user32.dll")] |
| 14 | + private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags); |
| 15 | + |
| 16 | + [DllImport("user32.dll")] |
| 17 | + private static extern bool UnhookWinEvent(IntPtr hWinEventHook); |
| 18 | + |
| 19 | + [DllImport("User32.dll")] |
| 20 | + private static extern IntPtr SendMessage(IntPtr hWnd, uint nMsg, int wParam, int lParam); |
| 21 | + |
| 22 | + private const uint WINEVENT_OUTOFCONTEXT = 0; |
| 23 | + private const uint EVENT_SYSTEM_ALERT = 0x0002; |
| 24 | + |
| 25 | + private const uint WM_GETOBJECT = 0x3D; |
| 26 | + |
| 27 | + // ref: http://www.chromium.org/developers/design-documents/accessibility |
| 28 | + private const int GOOGLE_CHROME_ACCESSIBILITY_OBJECT_ID = 1; |
| 29 | + |
| 30 | + private readonly IntPtr mWinEventHook; |
| 31 | + private readonly WinEventDelegate mEventDelegate; |
| 32 | + |
| 33 | + public ChromeAccessibilityWinEventHook() |
| 34 | + { |
| 35 | + mEventDelegate = OnEventReceived; |
| 36 | + mWinEventHook = SetWinEventHook(EVENT_SYSTEM_ALERT, EVENT_SYSTEM_ALERT, IntPtr.Zero, mEventDelegate, 0, 0, WINEVENT_OUTOFCONTEXT); |
| 37 | + } |
| 38 | + |
| 39 | + private void OnEventReceived(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) |
| 40 | + { |
| 41 | + if (idObject == GOOGLE_CHROME_ACCESSIBILITY_OBJECT_ID) |
| 42 | + { |
| 43 | + EventReceived = true; |
| 44 | + SendMessage(hwnd, WM_GETOBJECT, 0, idObject); |
| 45 | + |
| 46 | + // Chrome only enables accessibility if it gets a top-level IAccessible request, so let's make one first |
| 47 | + var _ = AccessibleObjectHelper.GetAccessibleObjectFromWindow(hwnd).accName; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public void Dispose() |
| 52 | + { |
| 53 | + UnhookWinEvent(mWinEventHook); |
| 54 | + } |
| 55 | + |
| 56 | + /// <summary> |
| 57 | + /// This flag is set true whenever an event is received. |
| 58 | + /// Set it false before the period of interest. |
| 59 | + /// </summary> |
| 60 | + public bool EventReceived { get; set; } |
| 61 | + } |
| 62 | +} |
0 commit comments