簡體   English   中英

檢查是否已在C#,Windows窗體中打開無模式對話框

[英]Check if modeless dialogue is already open in C#, Windows Forms

我想在單擊圖片后打開一個對話框,但是我也不希望用戶能夠打開一個已打開的對話框。

我也希望它是無模式的(當輔助對話框仍在后台打開時,它們可以使用主GUI)

private void pictureBox18_Click(object sender, EventArgs e)
        {
            ADCs ADCsdiag = new ADCs();
            ADCsdiag.Show();
        }

在此示例中,我可以通過單擊圖片打開ADCsdiag對話。 我想限制只進行一次或不進行這種對話。

在方法之外定義它,並訂閱其Closing事件。

您可以根據需要顯示它,並且當用戶“關閉”它時,您實際上可以取消關閉而只是將其隱藏。 如果他們反復按下按鈕,則該表格最多只能顯示一次。

public partial class Form1 : Form
{
    private ADCs ADCsdiag = new ADCs();

    public Form1()
    {
        InitializeComponent();

        ADCsdiag.Closing += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                ((ADCs)sender).Hide();
            };
    }

    private void pictureBox18_Click(object sender, EventArgs e)
    {
        ADCsdiag.Show();
    }
}

這是我在評論中提到的FormsCollection類:

public class FormsCollection : IEnumerable
{
    private Collection c = new Collection();

    public Form Item {
        get { return c.Item(index); }
    }

    public void Add(Form frm)
    {
        c.Add(frm);
    }

    public virtual IEnumerator GetEnumerator()
    {
        return c.GetEnumerator;
    }

    public void Remove(Form frm)
    {
        int itemCount = 0;

        for (itemCount = 1; itemCount <= c.Count; itemCount++) {
            if (object.ReferenceEquals(frm, c.Item(itemCount))) {
                c.Remove(itemCount);
                break;
            }
        }
    }
}

然后,您將需要在某個地方實例化FormsCollection ,然后在Form_Load中將其添加到集合中,如下所示:

formsCollection.Add(this);

並在Disposed

formsCollection.Remove(this);

如果已加載Form則可以Activate它,而不必打開新實例。

if (FormLoaded(yourForm.Name))
{
    yourForm.Activate()
}
else
{
    yourForm.Show()
}

這是FormLoaded函數:

public bool FormLoaded(string strFormName)
{
    bool functionReturnValue = false;
    foreach (Form f in Forms) {
        if (f.Name == strFormName) {
            functionReturnValue = true;
            break;
        }
    }
    return functionReturnValue;
}

您可以通過在局部變量中保留表單實例並在需要時實例化它來完成此操作:

private ADCs _ADCsdiag;

private void pictureBox18_Click(object sender, EventArgs e)
{
   if (_ADCsdiag == null) { 
      _ADCsdiag = new ADCs(); 
      _ADCsdiag.Closed += (s, e) =>
       {
          _ADCsdiag= null;
        };
   }
   ADCsdiag.Show();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM