[英]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.