2008/05/30

Windows Form: Control the Closing icon ("X" button)

If you set the control box property to true (Fig.1), the UI will then show the control box which contains MinimizeBox, MaximizeBox, and the "X" button.
Fig.1
The "X" button usually means close/exit this windows form (or application). Can we have more control of this behavior (or the "X" button)?

Yes, we can. In your code behind, create an event for the form you want to control like this:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
  DialogResult dr = MessageBox.Show("Do you really want to leave?", "Confirm Window", MessageBoxButtons.YesNoCancel);

  if (dr == DialogResult.No || dr == DialogResult.Cancel)
  {
    MessageBox.Show("That's my boy~");
    e.Cancel = true; //means cancel this event
  }
  else
    MessageBox.Show("Bad boy!");
}

Every time when user clicks on the "X" button to close the form, it will trigger the above event and perform whatever you design in there.

No comments:

Post a Comment