模拟按钮单击

时间:2010-07-01 16:14:53

标签: c# winforms

如何模拟视觉点击表单中的按钮(WinForms)?

我不是说:

Button_Press(MyButton, new KeyPressEventArgs());

我希望用户能够(直观地)看到被点击的按钮。

当然我不想用

SendKeys.Send("{ENTER}")

或其他此类功能。

5 个答案:

答案 0 :(得分:6)

Button1.PerformClick

很简单的一个班轮。你走了。

答案 1 :(得分:2)

您可以随时尝试White。我观察到它移动鼠标指针并在我的自动UI测试中明显点击Silverlight UI元素;我想WinForms会发生同样的情况,但我不能肯定地说。

答案 2 :(得分:1)

如果您使用RadioButton而不是普通Button,则可以将其.Appearance属性设置为“Button”,然后从其他位置修改其.Checked属性。

例如

this.radioButton1.Appearance = Appearance.Button;

然后致电:

this.radioButton1.Checked = true;

this.radioButton1.Checked = false;

它看起来就像一个常规按钮。

答案 3 :(得分:1)

没有干净的方法来做到这一点。我所知道的唯一方法是使用mouse_event中的user32.dll函数。这还要求您暂时将光标移动到所需位置,执行单击,然后再将其移回。

[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));
}

或者,您可以将其转换为扩展方法:

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, 
            globalLocation.X, globalLocation.Y, 0, 0);

        Cursor.Position = currLocation;
    }

    public static void ClickMouse(this Control target, Point localLocation)
    {
        ClickMouseLeftButton(target.PointToScreen(localLocation));
    }

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

这样您就可以拨打controlName.ClickMouse();

答案 4 :(得分:1)

这是一个非常简单的解决方案:

button1.Focus();
SendKeys.Send(" ");