• [转载]如何在MDI中使子窗体只保留一个实例(反射方法)


    出处:http://dev.csdn.net/author/Knight94/acd529d8a91a42f6ba5996babf1395d4.html

    作者:愚翁 

    转载:青弦 http://www.cnblogs.com/frostcity/archive/2008/08/21/1273310.html

    首先是通过子窗体类型名来判断是否打开新的子窗体,还是把原有的子窗体进行显示。 

    复制代码
     1/// <summary>
     2/// Open child window
     3/// </summary>
     4/// <param name="ChildTypeString"></param>

     5private void OpenWindow(string ChildTypeString)
     6{
     7   Form myChild = null;
     8   if (!ContainMDIChild(ChildTypeString))
     9   {
    10      // Get current process assembly
    11      Assembly assembly = Assembly.GetExecutingAssembly();
    12
    13      // Create data type using type string
    14      Type typForm = assembly.GetType(ChildTypeString);
    15
    16      // Create object using type's "InvokeMember" method
    17      Object obj = typForm.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, nullnullnull);
    18
    19      // Show child form 
    20      if (obj != null)
    21      {
    22         myChild = obj as Form;
    23         myChild.MdiParent = this;
    24         myChild.Show();
    25         myChild.Focus();
    26      }

    27   }

    28}

    29
    30/// <summary>
    31/// Search mdi child form by specific type string
    32/// </summary>
    33/// <param name="ChildTypeString"></param>
    34/// <returns><eturns>

    35private bool ContainMDIChild(string ChildTypeString)
    36{
    37   Form myMDIChild = null;
    38   foreach (Form f in this.MdiChildren)
    39   {
    40      if (f.GetType().ToString() == ChildTypeString)
    41      {
    42         // found it 
    43         myMDIChild = f;
    44         break;
    45      }

    46   }

    47
    48   // Show the exist form
    49   if (myMDIChild != null)
    50   {
    51      myMDIChild.TopMost = true;
    52      myMDIChild.Show();
    53      myMDIChild.Focus();
    54      return true;
    55   }

    56   else
    57      return false;
    58}
    复制代码

    以上两部分就可以对于每个子窗体只创建一个实例。那么调用以上代码就非常简单了。

    如:

    //Open a mdi child form which type named "MDIChild"
    OpenWindow( typeof( MDIChild ).ToString() );
  • 相关阅读:
    找到了2年前的一个微博小号
    Float Equal Problem
    有用的护肤品贴
    最近状态总结
    [Coursera]Machine Learning
    KMP算法(转载)
    [Leetcode] Median of Two Sorted Arrays
    [Algorithms(Princeton)] Week1
    [Algorithms(Princeton)] Week1
    [Leetcode] Binary Tree Maximum Path Sum
  • 原文地址:https://www.cnblogs.com/linyefeilyft/p/2918742.html
Copyright © 2020-2023  润新知