Closing an opening window

  • Thread starter Thread starter John Smith
  • Start date Start date
J

John Smith

Hey,

Posted this last week, but with the holidays and all I didn't get an
answer/solution, so I thought one of you might be able to help.

I need to:
a) Close a windows form from within the form's code itself
b) It must be able to occur after the form's constructor function is called
(like from another function that's called before .Show())
c) It must be able to occur before the form is actually viewable.

It's for security purposes.

If I add it to load, I get an error that you can't call close() or dispose()
while creating the window handle. I also tried doing it in the handlecreated
event for that reason, but I get the same error.

Any ideas (other than not calling .Show())?


Thx
 
Hello John,

Yeah, I have a good idea... Just have to security logic outside the form
that is about to be shown. If the security is good, then you show the form,
if not, just don't show. If that's not possible, just set the Visible property
of the form to false before you do Show(). That should do it.

I recommend the former method, but the latter is just a quick and dirty solution.
 
Thanks Hayato,

Yeah, I thought of that, but I was trying to avoid it because I'm adding it
to an existing large application with atleast 50 forms and many .Show()s
called. I'm also afraid a future programmer can accidentally bypass all
security by simply calling .Show() without doing the security check.

All the forms inherit from the same base form, so I was hoping to put the
logic right in there and then there would be no room for error. Guess it
can't be done though <sigh>.
 
John said:
All the forms inherit from the same base form, so I was hoping to put the
logic right in there and then there would be no room for error. Guess it
can't be done though <sigh>.

Why don't you override the Forms.Show() method in your base form class ? If
your check result is ok, call base.Show(), otherwise return without any
further action.

// Base class for your forms

public class MyFormsSuperclass : System.Windows.Forms.Form
{
public MyFormsSuperclass() : base()
{
}

public void Show()
{
if (!(this.isOkToOpen()))
{
return;
};

base.Show();
}

public virtual bool isOkToOpen()
{
return true;
}
}


// The Form you want to open or not, based on the
// result of isOkToOpen()

public class MyForm : MyFormsSuperclass
{

// lots of other stuff

public override bool isOkToOpen()
{
if (MessageBox.Show(this, "Open MyForm ?", "Question",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
return true;
};
return false;
}
}
 
ahh....perfect. I couldn't figure out how to override show. I started to
think you couldn't.
Thx a lot! Exactly what I wanted it to do!
 
Back
Top