0

How would you make an instance of a form open itself in a Modal way?

I tried this.ShowDialog() but it doesn't make the form appear modal (you can still access other forms). I guess this is because it is it's own parent form in if it shows itself, but I'm not sure.

My problem:

I have an application made of 2 forms:

  1. MainForm
  2. LoginForm

MainForm creates an instance of and opens LoginForm to ask the user to authenticate. LoginForm has a timer to regularly check and log the user in - I want this timer to open LoginForm modally. I know this could be achieved by putting the timer in MainForm but I would like to know how to make a form ShowDialog() an instance of itself.

Thanks in advance.

4

3 回答 3

2

确保您ShowDialog在以下时间致电InitializeComponent

public newForm()
{
    InitializeComponent();
    this.ShowDialog();
}

我的测试

我创建了一个名为Form2

public partial class Form2 : Form
{
    public Form2()
    {
        //this may not call in constractor 
        //InitializeComponent();
    }

    public void ShowModalForm()
    {
        InitializeComponent();
        ShowDialog();
    }
}

并在没有任何父级的情况下在 main 上启动它,它以模态方式启动:

static class Program
{
    [STAThread]
    static void Main()
    {
        new Form2().ShowModalForm();
        //Application.Run(new Form1());
    }
}
于 2012-07-12T10:28:01.977 回答
1

如果表单是顶级窗口(没有父窗口),则表单不会是模态的。另一方面,如果您的表单将有其他表单作为父表单,那么它将以模态方式打开(阻止父表单).ShowDialog()

于 2012-07-12T10:29:24.723 回答
0

这是您的选项 -LoginExpired在您的LoginForm. 在计时器滴答事件处理程序上引发此事件:

public partial class LoginForm : Form
{
    public event EventHandler LoginExpired;

    public LoginForm()
    {
        InitializeComponent();
        timer.Start();
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        OnLoginExpired();
    }

    protected virtual void OnLoginExpired()
    {
        if (Visible)
            return; // if this form visible, then user didn't authenticate yet

        if (LoginExpired != null)
            LoginExpired(this, EventArgs.Empty);
    }        
}

Main然后在您的方法上订阅此事件:

static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    using (LoginForm loginForm = new LoginForm())
    {
        if (loginForm.ShowDialog() != DialogResult.OK)
            return;

        loginForm.LoginExpired += new EventHandler(loginForm_LoginExpired);
        Application.Run(new MainForm());
    }
}

static void loginForm_LoginExpired(object sender, EventArgs e)
{
    LoginForm loginForm = (LoginForm)sender;
    if (loginForm.ShowDialog() != DialogResult.OK)
        throw new NotAuthenticatedException();
} 
于 2012-07-12T11:41:32.937 回答