创建按钮单击事件c#

我用了一个按钮

Button buttonOk = new Button(); 

以及其他代码,如何检测是否已单击创建的按钮? 并且如果点击该表格将关闭?

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

您需要一个事件处理程序,单击该按钮时将触发该事件处理程序。 这是一个快速的方法 –

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

如果您的按钮位于表单类中:

 buttonOk.Click += new EventHandler(your_click_method); 

(可能不完全是EventHandler

并在您的点击方法中:

 this.Close(); 

如果您需要显示一个消息框:

 MessageBox.Show("test"); 

创建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 }