创建按钮点击事件 c#

8
我用以下代码制作了一个按钮:
Button buttonOk = new Button();

除其他代码外,我如何检测是否单击了创建的按钮?并使其在单击后关闭表单?


你需要附加事件处理程序 buttonOk.Click += ... - Shadow The Spring Wizard
抱歉稍微修改了我的问题,但是我该如何做到这一点,以便它会打开一个MessageBox? - Froodle
MessageBox.Show("一些文本"); - NDJ
4个回答

16
    public MainWindow()
    {
        // This button needs to exist on your form.
        myButton.Click += myButton_Click;
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Message here");
        this.Close();
    }

1
对我不起作用,但谢谢你。 - Froodle
@FroodleStirling 您的表单上是否存在该按钮?不要在代码中创建新按钮,而是直接使用表单上的按钮。我已更新我的答案。也许您可以尝试一下。先将按钮放在表单上。 - Bob Horn
它会出现“需要对象引用”的错误。 - Froodle
@Bob Horn:EventHandler在哪里?它是如何工作的? - Manoj Weerasooriya
它简单地运行了。谢谢。 - MindRoasterMir
显示剩余2条评论

10

当按钮被点击时,您需要一个事件处理程序来触发。这里有一个快速的方法 -

  var button = new Button();
  button.Text = "my button";

  this.Controls.Add(button);

  button.Click += (sender, args) =>
                       {
                           MessageBox.Show("Some stuff");
                           Close();
                       };

但更好的方法是多了解一些关于按钮、事件等的知识。

如果您使用Visual Studio UI创建一个按钮,并在设计模式下双击按钮,这将为您创建事件并将其连接。然后,您可以转到设计器代码(默认为Form1.Designer.cs),在那里找到事件:

 this.button1.Click += new System.EventHandler(this.button1_Click);

你还会看到很多关于按钮设置的其他信息,例如位置等等,这些将帮助您按照自己的方式创建一个按钮,并提高您创建UI元素的理解。例如,在我的2012年机器上,一个默认按钮会给出这个:

        this.button1.Location = new System.Drawing.Point(128, 214);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 1;
        this.button1.Text = "button1";
        this.button1.UseVisualStyleBackColor = true;
在关闭表单方面,只需在事件处理程序中加入 Close(); 即可实现。
private void button1_Click(object sender, EventArgs e)
    {
       MessageBox.Show("some text");
       Close();
    }

1
如果您的按钮位于表单类中:
buttonOk.Click += new EventHandler(your_click_method);

(可能不是完全)与EventHandler相关)

在您的单击方法中:

this.Close();

如果您需要显示一个消息框:
MessageBox.Show("test");

抱歉稍微改变了我的问题,但是我该如何做到这一点,以便它会打开一个消息框? - Froodle

0
创建一个 Button 并将其添加到 Form.Controls 列表中,以在您的窗体上显示它:
Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45);  //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list

在这里创建按钮点击方法:

void buttonOk_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
            this.Close(); //all your choice to close it or remove this line
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接