How can I make multiple forms be closed using 1 hotkey using c#?

Morgenstern 40 Reputation points
2023-04-23T22:52:41.54+00:00

I want multiple forms to be closed when 1 hotkey is pressed, but I don't know how. I was thinking of using 1 form to close all of the forms, but I don't know how to do that.

Developer technologies C#
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2023-04-24T02:11:28.9733333+00:00

    Hi, welcome to Microsoft Q&A.

    You can use the PreviewKeyDown event to make the form get a hotkey and perform the corresponding operation.

    The following code implements the function of pressing the Esc key to close all forms.

            private void Form2_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
            {
                if (e.KeyCode == Keys.Escape)
                {
                    List<Form> formsToClose = new List<Form>(Application.OpenForms.Cast<Form>());
                    foreach (Form form in formsToClose)
                    {
                        form.Close();
                    }
                }
            }
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.