模態窗體(ShowDialog)打開後,後面的主窗體就不能做任何操作了。
本博客要實現非模態窗體(show)實現模態窗體(ShowDialog)的一些效果(主窗體關閉,子窗體也要關閉。子窗體只能打開一個。)
同時,保留非模態窗體的一些特性(主窗體和子窗體都能操作,比如文本的書寫等)。
現實的一些用處:
1、比如要在主窗體中寫已有的內容,用子窗體顯示這些已有的內容(一般信息比較多,無法在主窗體中用某個空間顯示完全)以供參考。
2、直接點擊子窗體中的信息,在主窗體中顯示出來。
等等
代碼如下:
FormA----主窗體
FormB----子窗體
view plaincopy to clipboardprint?
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace BasicWindowsApplication
{
public partial class FormA : Form
{
FormB formB = null;
public FormA()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (formB == null)
{
formB = new FormB(this);//這一步很重要
formB.CloseFrm += new EventHandler(frmA_CloseFrm);
formB.Show();
}
else
{
formB.TopMost = true;
}
}
/// <summary>
/// 窗體關閉事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void frmA_CloseFrm(object sender, EventArgs e)
{
formB = null;
}
/// <summary>
/// 窗體關閉事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmA_FormClosed(object sender, FormClosedEventArgs e)
{
if (formB != null)
{
formB.Dispose();
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace BasicWindowsApplication
{
public partial class FormA : Form
{
FormB formB = null;
public FormA()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (formB == null)
{
formB = new FormB(this);//這一步很重要
formB.CloseFrm += new EventHandler(frmA_CloseFrm);
formB.Show();
}
else
{
formB.TopMost = true;
}
&nb