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 downWParam) = button switch
{
MouseButton.Left => (NativeMethods.WmLButtonDown, NativeMethods.MkLButton),
MouseButton.Right => (NativeMethods.WmRButtonDown, NativeMethods.MkRButton),
_ => throw new ArgumentOutOfRangeException(nameof(button)),
};
if (!NativeMethods.PostMessageW(hWnd, down, downWParam, lParam))
return false;
uint up = button == MouseButton.Left ? NativeMethods.WmLButtonUp : NativeMethods.WmRButtonUp;
return NativeMethods.PostMessageW(hWnd, up, 0, lParam);
}
private static nint MakeLong(int low, int high)
{
return (nint)((uint)low | ((uint)high << 16));
}
}