我用以下代码制作了一个按钮:
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
}
buttonOk.Click += ...
。 - Shadow The Spring Wizard