简体   繁体   中英

Disable Close Button

I have a form that a user uses to select the level when a Game starts. I want to disable the close button such that a user cannot close the form (The user will click some buttons to select the level).

I have been able to stop the user from closing the form if a button is not clicked using

    bool _Next = false;
    public Form1()
    {
        InitializeComponent();
        button1.Click += new EventHandler(button_Click);
        button2.Click += new EventHandler(button_Click);
        button3.Click += new EventHandler(button_Click);

    }

    void button_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;

        if (btn == button1)
        {
            Level(1);
        }
        else if (btn == button2)
        {
            Level(2);
        }
        else if (btn == button3)
        {
            Level(3);
        }
        _Next = true;
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (_Next == true)
        {
        }
        else
        {
            e.Cancel = true;
        }
    }

This is quite long. I want to know if there is any way i can just disable or hide the form close button

You're already disabling the close button. In your FormClosing event you cancel the event:

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

This code works perfectly; I just tested it to make sure.

You can hide the Controls of the form with:

this.ControlBox = false;

The above will remove the maximize , minimize and close button from the right upper corner.

The above is also accessible on the Visual Studio when you select the form itself at the properties tab.

You can override the OnClosing method:

protected override void OnClosing(CancelEventArgs e)
{
    if (!_Next)
    {
        e.Cancel = true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM