子窗体和父窗体问题!!
现在有一个父窗体mainfrm,点击父窗体mainfrm菜单弹出子窗体childfrm。怎么才能实现:随便你点多少次父窗体mainfrm菜单,始终只弹出一个子窗体childfrm啊。
------解决方案--------------------其实这个问题,就是经典的23种设计模式中的单件模式(singleton),下面用c#实现之:
首先我们有2个windows form,主窗体叫form1,子窗体叫childform。在主窗体中加入一menu,用来实例化子窗体,我们在form1.cs中写入下代码:
private static childform childform; //静态变量,保存唯一实例
private void menuitem2_click(object sender, system.eventargs e)
{
childform childform = getchildform(); //获取子窗体对象
childform.show(); //显示之
}
private childform getchildform()
{
//先后次序不能错,前一个条件用来判断是否是第一次,后一个条件用来判断子窗体是否被关闭了
if( childform == null || childform.isdisposed )
{ //第一次实例化也好,被关了也好,都重新实例化
childform = new childform();
childform.mdiparent = this;
}
return childform;
}
------解决方案--------------------以前我也用public static这种方法,后来觉得不好,占内存,也不符合编码规范,就换了种思路来实现。
2005下使用:
/// <summary>
/// 查找是否已创建窗体
/// </summary>
/// <param name= "FormName "> 窗体Name </param>
/// <returns> </returns>
public static bool SearchAllForm(string FormName)
{
for (int i = 0; i < Application.OpenForms.Count; i++)
{
if (Application.OpenForms[i].Name == FormName)
{
return true;
}
}
return false;
}
2003下使用:
[DllImport( "User32.dll ", EntryPoint = "FindWindow ")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport( "user32.dll ", EntryPoint = "FindWindowEx ")] //找子窗体
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport( "User32.dll ", EntryPoint = "SendMessage ")] //用于发送信息给窗体
private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);
/// <summary>
/// 查找是否已创建窗体
/// </summary>
/// <param name= "FormTitle "> 标题名称 </param>
/// <returns> </returns>
public static bool SearchForm(string FormTitle)
{
IntPtr ParenthWnd = new IntPtr(0);
IntPtr EdithWnd = new IntPtr(0);
//查到窗体,得到整个窗体
ParenthWnd = FindWindow(null,FormTitle);
if (!ParenthWnd.Equals(IntPtr.Zero))
{
return true;
}
else
{
return false;
}
}
------解决方案--------------------//在你的主form class里面增加下面这个函数,传入要激活或要新创建的子窗体
private CheckChildFrmExists(string ChildName)
{
foreach(Form newFrm in this.MdiChildren)
{
if(childFrm.Name == childFrmName)
{
if(childFrm.WindowState == FormWindowState.Minimized)
childFrm.WindowState = FormWindowState.Normal;
childFrm.Activate();
return true;
}
}
}
//最后在调用子窗体的代码里面增加调用上面的函数的代码,如下
if (this.checkChildFrmExist( "WareDataManage ") == true)
{
return;
}
WareDataManage newFrm = new WareDataManage(true);
newFrm.MdiParent = this;
newFrm.Show();