Can a form tell if there are any modal windows open?

后端 未结 6 2020
庸人自扰
庸人自扰 2020-12-14 07:08

How, being inside the main form of my WinForm app can I tell if there are any modal windows/dialogs open that belong to the main form?

6条回答
  •  失恋的感觉
    2020-12-14 07:55

    This is an illustration why this answer is correct and the assumptions made in this answer are sometimes wrong.

    if (MyForm.CanFocus == false && MyForm.Visible == true)
    {
        // we are modal            
    }
    

    This works for modal shown sub Forms and for MessageBoxes.


    Some demo code:

    private void modalTest_Click(object sender, EventArgs e)
    {
        // Timer which fires 100ms after the first message box is shown
        System.Windows.Forms.Timer canFocusTimer = new System.Windows.Forms.Timer();
        canFocusTimer.Tick += CanFocusTimer_Tick;
        canFocusTimer.Interval = 100;
        canFocusTimer.Start();
        
        // First MessageBox shows that CanFocus == true
        MessageBox.Show($"First MessageBox: { nameof(this.CanFocus) } == { this.CanFocus }");
    }
    
    private void CanFocusTimer_Tick(object sender, EventArgs e)
    {
        (sender as System.Windows.Forms.Timer).Stop();
    
        // Even though there is already a MessageBox shown the second gets
        // displayed. But now CanFocus == false
        MessageBox.Show($"Second MessageBox: { nameof(this.CanFocus) } == { this.CanFocus }");
    }
    

    Result:

提交回复
热议问题