Frage

I know this is very simple question, but I am looking for neat and clean suggestion. My application is an MDI application. Created a base form which is being used in the whole applicaiton. There are couple of forms which we dont want user to close so to avoid human mistakes we have planned to not allow the user to close those forms.

I have tried to setting e.cancel = true in form closing event, but it seems its not working can somebody give me some suggestions please?

Edit:

Private void FrmTask_FormClosing(object sender, FormClosingEventArgs e)
        {         
                e.Cancel = true;
        }

The problem is that when I am using this code, none of the form in my MDI application are closing, even the main MDI Parent form.

War es hilfreich?

Lösung

You could also not show the close button:

http://blogs.msdn.com/b/atosah/archive/2007/05/18/disable-close-x-button-in-winforms-using-c.aspx

Cody Gray provided a better link in the comments that also disallows the Alt-F4 close:

https://stackoverflow.com/a/4655948/366904

Andere Tipps

Presumably the issue here is you want the window to close when the app exists, but not if the user tries to close it manually.

To do this you will have to have a manual override, say a variable called allowShutdown defined, and have a method that can set this when the MdiParent is closing.

private void Form_Closing(object sender, EventArgs e)
{
  if( !allowShutdown) e.Cancel = true;
}

public void ForceShutdown()
{
  allowShutdown = true;
  Close();
}

And then in your parent form:

private void Form_Closing(object sender, EventArgs e)
{
  if( childForm != null ) childForm.ForceShutdown();
}

This assumes you are maintaining a reference to the child form in your parent form when you create it. Combine this with the ability to hide the close button mentioned in the other post and you should have a working solution.

I suspect FormClosingEventArgs.CloseReason would give you enough information to determine whether to conditionally cancel the Close.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top