Hide form instead of closing when close button clicked

前端 未结 7 1838
南旧
南旧 2020-11-28 08:47

When a user clicks the X button on a form, how can I hide it instead of closing it?

I have tried this.hide() in FormClosing but

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 09:06

    I've commented in a previous answer but thought I'd provide my own. Based on your question this code is similar to the top answer but adds the feature another mentions:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.UserClosing) 
        {
            e.Cancel = true;
            Hide();
        }
    }
    

    If the user is simply hitting the X in the window, the form hides; if anything else such as Task Manager, Application.Exit(), or Windows shutdown, the form is properly closed, since the return statement would be executed.

提交回复
热议问题