当用户按下ESC按钮时,如何关闭提示?

时间:2014-01-19 22:23:38

标签: c# winforms sendkeys cancel-button

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调用方法/属性(没有在属性部分中进行可视化编辑),如果关闭按钮则关闭按钮?

2 个答案:

答案 0 :(得分:3)

这是另一种关闭表单的方法,只需按下模型表单的退出按钮,而不放置任何取消按钮:

prompt.KeyPreview = true;
prompt.KeyDown += (sender, e) => 
{ 
    if (e.KeyCode == Keys.Escape) prompt.DialogResult = DialogResult.Cancel; // you can also call prompt.Close() here
};

答案 1 :(得分: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将导致表单自行关闭,而不需要单击事件来关闭表单。

相关问题