Hide form instead of closing when close button clicked

前端 未结 7 1866
南旧
南旧 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:01

    Note that when doing this (several answers have been posted) that you also need to find a way to ALLOW the user to close the form when they really want to. This really becomes a problem if the user tries to shut down the machine when the application is running, because (at least on some OS) this will stop the OS from shutting down properly or efficiently.

    The way I solved this was to check the stack trace - there are differences between when the user tries to click the X vs when the system tries to end the application in preparation for shutdown.

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        StackTrace trace = new StackTrace();
        StackFrame frame;
        bool bFoundExitCommand = false;
        for (int i = 0; i < trace.FrameCount; i++)
        {
            frame = trace.GetFrame(i);
            string methodName = frame.GetMethod().Name;
            if (methodName == "miExit_Click")
            {
                bFoundExitCommand = true;
                Log("FormClosing: Found Exit Command ({0}) - will allow exit", LogUtilityLevel.Debug3, methodName);
            }
            if (methodName == "PeekMessage")
            {
                bFoundExitCommand = true;
                Log("FormClosing: Found System Shutdown ({0}) - will allow exit", LogUtilityLevel.Debug3, methodName);
            }
            Log("FormClosing: frame.GetMethod().Name = {0}", LogUtilityLevel.Debug4, methodName);
        }
        if (!bFoundExitCommand)
        {
            e.Cancel = true;
            this.Visible = false;
        }
        else
        {
            this.Visible = false;
        }
    }
    

提交回复
热议问题