使用.PerformClick()获取EventArgument

时间:2013-02-28 08:06:07

标签: c#

我尝试创建动态按钮并模拟鼠标点击而不使用.PerformClick导入Dll。

代码:

for (int i = 0; i < save.Count; i++)
{
    Button tempButtonForClick = new Button();
    tempButtonForClick.Location = save[i].SaveRegion.Location;
    Cursor.Position = save[i].SaveRegion.Location;
    tempButtonForClick.Size = save[i].SaveRegion.Size;
    tempButtonForClick.Click += new EventHandler(MainPanelClicks);
    MainPanel.Controls.Add(tempButtonForClick);
    tempButtonForClick.PerformClick();
    ...
}

问题是,我用该方法得到一个空的EventArgs。有没有办法获得“正常”的EventArgument?

提前致谢。

1 个答案:

答案 0 :(得分:1)

我真的不鼓励你这样做,但如果你真的想要它,那么它就是这样。 (最好的方法是创建一个额外的控制层并从该层触发事物 - Action Manager类层)。

首先,创建一个很好的小扩展方法容器类,如:

public static class ButtonExtensions {

    // Button indirectly extends Control
    // Control has a protected method: protected void OnClick(EventArgs e);
    // you can't call it directly, you need to do it via reflection
    private static readonly MethodInfo controlsOnClickMethod = typeof(Control).GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic);

    // Although the second parameter of the Button.Click event
    // is syntactically: EventArgs
    // at runtime, it is usually a MouseEventArgs
    // so that's what we're going to send it
    public static void PerformClickEx(this Button @this, MouseEventArgs args) {
        ButtonExtensions.controlsOnClickMethod.Invoke(@this, new object[] { args });
    }

}

你怎么用这个?真的很容易:

public class Foo {

    private Button someButton;

    public void Bar() {
        this.someButton.PerformClickEx(new MouseEventArgs(MouseButtons.Right, 1, 100, 100, 2));
    }
}

你得到了非常需要的,非空的,充满鼠标信息的EventArgs(实际上是一个MouseEventArgs):)