You can use
SendInput() or
mouse_event() from the Win32 API (you'll need to use p/invoke to call these from .NET). The latter has been replaced by the former, but it's a simpler function. If you choose to use
SendInput() instead, it can handle both mouse and keyboard events, but you'll need to simulate unions in C#. You can do this with the various structure member alignment and layout directives, but since
mouse_event() is simpler to use, I'll give an example with that:
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace YourNamespaceHere
{
public static class VirtualMouse
{
// import the necessary API function so .NET can
// marshall parameters appropriately
[DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
// constants for the mouse_input() API function
private const int MOUSEEVENTF_MOVE = 0x0001;
private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
private const int MOUSEEVENTF_LEFTUP = 0x0004;
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const int MOUSEEVENTF_RIGHTUP = 0x0010;
private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
private const int MOUSEEVENTF_MIDDLEUP = 0x0040;
private const int MOUSEEVENTF_ABSOLUTE = 0x8000;
// simulates movement of the mouse. parameters specify changes
// in relative position. positive values indicate movement
// right or down
public static void Move(int xDelta, int yDelta)
{
mouse_event(MOUSEEVENTF_MOVE, xDelta, yDelta, 0, 0);
}
// simulates movement of the mouse. parameters specify an
// absolute location, with the top left corner being the
// origin
public static void MoveTo(int x, int y)
{
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x, y, 0, 0);
}
// simulates a click-and-release action of the left mouse
// button at its current position
public static void LeftClick()
{
mouse_event(MOUSEEVENTF_LEFTDOWN, Control.MousePosition.X, Control.MousePosition.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, Control.MousePosition.X, Control.MousePosition.Y, 0, 0);
}
}
}
Note that mouse movement and position values are not given in pixels, but rather 'mickeys'; a
mickey is the smallest increment of motion that the mouse can detect. Mouse sensitivity (ie, in the Windows control panel) just changes the number of mickeys the mouse must move in order for Windows to actually move the pointer.
If you like, you can add to this class to make it more full-featured, like support for the other buttons, support for dragging (you just have separate 'press' and 'release' methods, rather than combining them as in the 'click' method).
[edit] For the record, this functionality exists at a pretty low level. I'm fairly certain that
mouse_event() is just the API function invoked by the mouse driver, so you can spoof mouse input for any software you like; it's not limited to the application with focus. [/edit]