using System.Runtime.InteropServices; using WhiteMagic.Native; namespace WhiteMagic.Input; /// /// Mouse buttons supported by . /// public enum MouseButton { /// The left mouse button. Left, /// The right mouse button. Right, } /// /// Simulates keyboard and mouse input directed at a target window via window messages. /// public sealed class InputSimulator { /// /// Sends a sequence of character messages to . /// /// if every character was posted successfully. public bool SendKeys(IntPtr hWnd, string text) { if (text is null) throw new ArgumentNullException(nameof(text)); if (hWnd == IntPtr.Zero) return false; foreach (char c in text) { if (!NativeMethods.PostMessageW(hWnd, NativeMethods.WmChar, (nuint)c, 0)) return false; } return true; } /// /// Sends a mouse click at client-area coordinates , /// to . /// /// if the click was posted successfully. public bool SendMouseClick(IntPtr hWnd, int x, int y, MouseButton button) { if (hWnd == IntPtr.Zero) return false; nint lParam = MakeLong(x, y); (uint down, uint up) = button switch { MouseButton.Left => (NativeMethods.WmLButtonDown, NativeMethods.WmLButtonUp), MouseButton.Right => (NativeMethods.WmRButtonDown, NativeMethods.WmRButtonUp), _ => throw new ArgumentOutOfRangeException(nameof(button)), }; if (!NativeMethods.PostMessageW(hWnd, down, 0, lParam)) return false; return NativeMethods.PostMessageW(hWnd, up, 0, lParam); } private static nint MakeLong(int low, int high) { return (nint)((uint)low | ((uint)high << 16)); } }