0

我尝试使用 .PerformClick 创建动态按钮并在不导入 Dll 的情况下模拟 Mouseclick。

代码:

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?

提前致谢。

4

1 回答 1

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):)

于 2013-02-28T08:40:24.863 回答