Hi @mc , Welcome to Microsoft Q&A,
You need to set the appropriate dwFlags
in the MOUSEINPUT
structure for mouse down and mouse up events. Additionally, ensure the dx
and dy
fields are set to 0 if you don't want to move the mouse cursor.
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
public class Program
{
[DllImport("user32.dll")]
public extern static uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
[StructLayout(LayoutKind.Sequential)]
public struct INPUT
{
public int type;
public InputUnion U;
}
[StructLayout(LayoutKind.Explicit)]
public struct InputUnion
{
[FieldOffset(0)]
public MOUSEINPUT mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
[FieldOffset(0)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct HARDWAREINPUT
{
public uint uMsg;
public ushort wParamL;
public ushort wParamH;
}
private const int INPUT_MOUSE = 0;
private const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
private const uint MOUSEEVENTF_LEFTUP = 0x0004;
public static async Task Main(string[] args)
{
// Simulate a left mouse button click
var input = new INPUT[2];
// Mouse down
input[0] = new INPUT
{
type = INPUT_MOUSE,
U = new InputUnion
{
mi = new MOUSEINPUT
{
dwFlags = MOUSEEVENTF_LEFTDOWN,
}
}
};
// Mouse up
input[1] = new INPUT
{
type = INPUT_MOUSE,
U = new InputUnion
{
mi = new MOUSEINPUT
{
dwFlags = MOUSEEVENTF_LEFTUP,
}
}
};
// Send the input
SendInput((uint)input.Length, input, Marshal.SizeOf(typeof(INPUT)));
// Optional delay
await Task.Delay(300);
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.