Search code examples
c#winformssendkeyscancel-button

How do I close my prompt when the user presses the ESC 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;
}

So this is my prompt and I want to make a button so that it can close. Now I know this has been asked before but that is because they are using a default form.

This is my CancelButton and what it will do.

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

However, I'm not using a different class. I'm using the same class. What would be the 1 call method/property (without visually editing it in the properties section) to close the button if it is closed?


Solution

  • Here is another way to close your form with pressing escape button for a model form without placing any cancel button:

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