Using the built-in automation of the WPF user interface, it is easy (although quite a lot) to send a left-click event to an AutomationElement element (for example, a button):
InvokePattern invokePattern = (InvokePattern) element.GetCurrentPattern(InvokePattern.Pattern);
invokePattern.Invoke();
However, there seems to be no built-in way to send right clicks to the same element. I put up with using P / Invoke to call SendInput , but I can't get it to work. With the code below, when I call RightClick (), the context menu appears right where the cursor is, and not in the element that I assume will be right-clicked. Thus, it seems that it ignores the coordinates that I use, and just uses the current cursor location.
public static void RightClick(this AutomationElement element)
{
Point p = element.GetClickablePoint();
NativeStructs.Input input = new NativeStructs.Input
{
type = NativeEnums.SendInputEventType.Mouse,
mouseInput = new NativeStructs.MouseInput
{
dx = (int) p.X,
dy = (int) p.Y,
mouseData = 0,
dwFlags = NativeEnums.MouseEventFlags.Absolute | NativeEnums.MouseEventFlags.RightDown,
time = 0,
dwExtraInfo = IntPtr.Zero,
},
};
NativeMethods.SendInput(1, ref input, Marshal.SizeOf(input));
input.mouseInput.dwFlags = NativeEnums.MouseEventFlags.Absolute | NativeEnums.MouseEventFlags.RightUp;
NativeMethods.SendInput(1, ref input, Marshal.SizeOf(input));
}
internal static class NativeMethods
{
[DllImport("user32.dll", SetLastError = true)]
internal static extern uint SendInput(uint nInputs, ref NativeStructs.Input pInputs, int cbSize);
}
internal static class NativeStructs
{
[StructLayout(LayoutKind.Sequential)]
internal struct Input
{
public NativeEnums.SendInputEventType type;
public MouseInput mouseInput;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MouseInput
{
public int dx;
public int dy;
public uint mouseData;
public NativeEnums.MouseEventFlags dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
}
internal static class NativeEnums
{
internal enum SendInputEventType : int
{
Mouse = 0,
Keyboard = 1,
Hardware = 2,
}
[Flags]
internal enum MouseEventFlags : uint
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800,
Absolute = 0x8000,
}
}