2
public int dialog()
{
    Form prompt = new Form(); // creates form

    //dimensions
    prompt.Width = 300;
    prompt.Height = 125;

    prompt.Text = "Adding Rows"; // title

    Label amountLabel = new Label() { Left = 75, Top = 0, Text = "Enter a number" }; // label for prompt
    amountLabel.Font = new Font("Microsoft Sans Serif", 9.75F);
    TextBox value = new TextBox() { Left = 50, Top = 25, Width = prompt.Width / 2 }; // text box for prompt
    //value.Focus();
    Button confirmation = new Button() { Text = "Ok", Left = prompt.Width / 2 - 50, Width = 50, Top = 50 }; // ok button
    confirmation.Click += (sender, e) => { prompt.Close(); }; // if clicked it will close

    prompt.AcceptButton = confirmation;

    // adding the controls
    prompt.Controls.Add(value);
    prompt.Controls.Add(confirmation);
    prompt.Controls.Add(amountLabel);
    prompt.ShowDialog();

    int num;
    Int32.TryParse(value.Text, out num);
    return num;
}

所以这是我的提示,我想制作一个按钮以便它可以关闭。现在我知道以前有人问过这个问题,但那是因为他们使用的是默认表单。

这是我的CancelButton,它会做什么。

prompt.CancelButton = this.Close(); // not working

但是,我没有使用其他类。我正在使用相同的课程。如果关闭按钮,那么关闭按钮的 1 调用方法/属性(没有在属性部分中对其进行可视化编辑)是什么?

4

2 回答 2

3

这是另一种在不放置任何取消按钮的情况下按下模型表单的退出按钮来关闭表单的方法:

prompt.KeyPreview = true;
prompt.KeyDown += (sender, e) => 
{ 
    if (e.KeyCode == Keys.Escape) prompt.DialogResult = DialogResult.Cancel; // you can also call prompt.Close() here
};
于 2014-01-19T22:56:39.767 回答
2

如果您需要区分取消关闭和确认关闭,那么您需要两个单独的按钮

Button cancellation = new Button() 
{ Text = "Cancel", Left = prompt.Width / 2 + 10, Width = 50, Top = 50 }; 

prompt.CancelButton = cancellation;
cancellation.DialogResult = DialogResult.Cancel;

您的确认按钮也需要设置 DialogResult 属性

confirmation.DialogResult = DialogResult.OK;

所以你可以得到 ShowDialog 的结果

if(DialogResult.OK == prompt.ShowDialog())
{
    int num;
    Int32.TryParse(value.Text, out num);
    return num;
}
else
    return 0; // Or whatever to signal failure

顺便说一句,将 DialogResult 属性设置为与 DialogResult.None 不同的值将导致表单自行关闭,而无需单击事件来关闭表单。

于 2014-01-19T22:36:20.977 回答