开发者

How to prevent a form to show up in the constructor?

开发者 https://www.devze.com 2022-12-21 06:55 出处:网络
I have a C# application and I am trying to prevent a form to show up in the constructor. I launch the form like this:

I have a C# application and I am trying to prevent a form to show up in the constructor.

I launch the form like this:

Form1 f = new Form1();
f.ShowDialog();

what do I have to do in the Constructor so the f.ShowDialog should not launch and co开发者_StackOverflow社区ntinue code execution.


Can't you add a public property (ShowTheDialog in this example) in the constructor for f and set to true if you want to call f.ShowDialog

Form1 f = new Form1();
if(f.ShowTheDialog) {
  f.ShowDialog();
}


I think Pentium10 wants to be able to specify via the constructor whether, at a later time, ShowDialog is allows to actually display a dialog. In other words, he really wants to be able to override ShowDialog, so that in his own ShowDialog he can check this magic permission variable and either bail, or call the base ShowDialog.

I'm not sure if this is technically correct, but it does seem to work. Pentium10, in your Window class, create another public method called ShowDialog that hides the inherited ShowDialog. Then inside, check your variable and only if it's allowed, call the base's ShowDialog method, like this:

public partial class Window3 : Window
{
    bool _allowed { get; set; }
    public Window3( bool allowed)
    {
        _allowed = allowed;
        InitializeComponent();
    }

    public void ShowDialog()
    {
        if( !_allowed)
            return;
        else
            base.ShowDialog();
    }
}


(I'm no windows forms expert, but) couldn't you set a flag in your constructor, whether the form can be shown or not, then override the OnLoad() method, and if your flag is false, hide the form immediately, e.g:

private bool _canShow = true;
public Form1()
{
  _canShow = ...;
}

protected override OnLoad(EventArgs e)
{
  if (!_canShow) Close();
  base.OnLoad(e);
}


How about calling ShowDialog in the constructor itself if it needs to be shown ?

And then you only need to do:

Form1 f = new Form1();
0

精彩评论

暂无评论...
验证码 换一张
取 消