C# 通过代码触发按钮点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14024963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Triggering a button click through code
提问by Ralt
So I have the following code for when the "Add player" button is clicked
因此,当单击“添加播放器”按钮时,我有以下代码
private void addPlayerBtn_Click_1(object sender, EventArgs e)
{
//Do some code
}
I want to trigger this code from my SDK however. Here is what I have tried
但是,我想从我的 SDK 触发此代码。这是我尝试过的
private void command()
{
addPlayerBtn_Click_1(object sender, EventArgs e);
}
I get lots of errors as soon as I put in the line
我一排队就收到很多错误
addPlayerBtn_Click_1(object sender, EventArgs e)
Could somebody please tell me how to write the code so that I can trigger an event by just writting it in code?
有人可以告诉我如何编写代码,以便我只需将其写入代码即可触发事件吗?
采纳答案by Dave Zych
For one, when calling a method, you don't declare the type of the parameter, just the value.
一方面,调用方法时,不声明参数的类型,只声明值。
So this:
所以这:
addPlayerBtn_Click_1(object sender, EventArgs e);
Should be
应该
addPlayerBtn_Click_1(sender, e);
Now, you'll have to declare sender
and e
. These can be actual objects, if you have event args to pass, or:
现在,您必须声明sender
和e
。这些可以是实际对象,如果您要传递事件参数,或者:
addPlayerBtn_Click_1(null, EventArgs.Empty);
The above can be used in either WinForms or ASP.NET. In the case of WinForms, you can also call:
以上可以在 WinForms 或 ASP.NET 中使用。在 WinForms 的情况下,您还可以调用:
addPlayerBtn.PerformClick();
回答by Ben Voigt
When you call a function, you provide actual arguments, which are values, not formal arguments, which are types and parameter names.
当您调用函数时,您提供的是实际参数,即值,而不是形式参数,即类型和参数名称。
Change
改变
addPlayerBtn_Click_1(object sender, EventArgs e);
to
到
addPlayerBtn_Click_1(addPlayerBtn, EventArgs.Empty);
回答by gdoron is supporting Monica
addPlayerBtn_Click_1(object sender, EventArgs e);
Should be:
应该:
addPlayerBtn_Click_1(this, new EventArgs());
回答by ispiro
addPlayerBtn_Click_1(null, null);
This works if you don't need the information in sender
and e
.
如果您不需要sender
和 中的信息,这将起作用e
。
回答by Steve Wellens
You are not using the sender or the events so you can call the function directly like this:
您没有使用发送者或事件,因此您可以像这样直接调用该函数:
addPlayerBtn_Click_1(null, null);
回答by Majed Leader
private void command()
{
addPlayerBtn.PerformClick();
}