如何在MDI中使子窗体只保留一个实例

由于在 MDI 中,子窗体会很多,那么在我以前一篇文章中所提到的方法就有些繁琐了。为了能适应多个子窗体,并对于每个子窗体只保留一个实例,那么我就用一个新的方法来替换,即用反射方法来作处理。

 

大致代码如下。

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

    using System.Reflection;

    /// <summary>

    /// Open child window

    /// </summary>

    /// <param name="ChildTypeString"></param>

    private void OpenWindow( string ChildTypeString )

    {

        Form myChild = null;

        if( !ContainMDIChild( ChildTypeString ) )

        {

            // Get current process assembly

            Assembly assembly = Assembly.GetExecutingAssembly();

 

            // Create data type using type string

            Type typForm = assembly.GetType( ChildTypeString );

 

            // Create object using type's "InvokeMember" method

            Object obj = typForm.InvokeMember(

                null,

                BindingFlags.DeclaredOnly |

                BindingFlags.Public | BindingFlags.NonPublic |

                BindingFlags.Instance | BindingFlags.CreateInstance,

                null,

                null,

                null );

 

            // Show child form

            if( obj != null )

            {

                myChild = obj as Form;

                myChild.MdiParent = this;

                myChild.Show();

                myChild.Focus();

            }

        }

    }

 

    /// <summary>

    /// Search mdi child form by specific type string

    /// </summary>

    /// <param name="ChildTypeString"></param>

    /// <returns></returns>

    private bool ContainMDIChild( string ChildTypeString )

    {

        Form myMDIChild = null;

        foreach(Form f in this.MdiChildren)

        {

            if( f.GetType().ToString() == ChildTypeString )

            {

                // found it

                myMDIChild = f;

                break;

            }

        }

 

        // Show the exist form

        if( myMDIChild != null)

        {

            myMDIChild.TopMost = true;

            myMDIChild.Show();

            myMDIChild.Focus();

            return true;

        }

        else

            return false;

    }

 

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

如:

    //Open a mdi child form which type named "MDIChild"

    OpenWindow( typeof( MDIChild ).ToString() );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值