Alex Rivera | Logout

Simulate button click

Asked 2010-07-01T16:14:52.530
14

How can I simulate a visual click on a button in my form (WinForms)?

I don't mean:

Button_Press(MyButton, new KeyPressEventArgs());

I want the user to see (visually) the button being clicked.

Of course I don't want to use

SendKeys.Send("{ENTER}")

or other functions of this kind.

Edit
Report

2 Answers

2

There is no clean way to do this. The only way I'm aware of is to use the mouse_event function from user32.dll. This also requires that you temporarily move the cursor to the desired location, perform the click, then move it back.

[DllImport("user32.dll", CharSet = CharSet.Auto, 
 CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, 
    long cButtons, long dwExtraInfo);

private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;

public void ClickMouseLeftButton(Point globalLocation)
{
    Point currLocation = Cursor.Position;

    Cursor.Position = globalLocation;

    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 
        globalLocation.X, globalLocation.Y, 0, 0);

    Cursor.Position = currLocation;
}

public void ClickControl(Control target, Point localLocation)
{
    ClickMouseLeftButton(target.PointToScreen(localLocation));
}

public void ClickControl(Control target)
{
    ClickControl(target, new Point(target.Width / 2, target.Height / 2));
}

Alternatively, you could turn this into an extension method:

public static class ControlExtensions
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, 
     CallingConvention = CallingConvention.StdCall)]
    private static extern void mouse_event(long dwFlags, long dx, long dy, 
        long cButtons, long dwExtraInfo);

    private const int MOUSEEVENTF_LEFTDOWN = 0x02;
    private const int MOUSEEVENTF_LEFTUP = 0x04;
    private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
    private const int MOUSEEVENTF_RIGHTUP = 0x10;

    private static void ClickMouseLeftButton(Point globalLocation)
    {
        Point currLocation = Cursor.Position;

        Cursor.Position = globalLocation;

        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,
answered 2010-07-01T16:50:22.850
2

You could always try White. I've observed it moving the mouse pointer and visibly clicking on Silverlight UI elements in my automated UI tests; I imagine the same would happen with WinForms but I can't say for certain.

answered 2010-07-02T02:57:49.780

Your Answer