将方法调用插入InitializeComponent

时间:2017-03-07 09:33:26

标签: c# winforms codedom

我正在尝试扩展InitializeComponent方法的默认内容。 我想在那里添加几个方法调用。

问题是 - 我需要将这些调用放在InitializeComponent方法的特定位置。

例如,我想在每次字段初始化后调用我的方法:

    this.ctrl1 = new UserControl();
    MyMethod(); // <---- call of my method
    this.ctrl2 = new UserControl();
    MyMethod(); // <---- call of my method
    this.SuspendLayout();
    .................................

我试图更改CodeDomSerializer的一点默认行为。我的想法是找到每个CodeFieldReferenceExpression并在其后添加CodeMethodReferenceExpression

public class CodeDomSerializerEx : CodeDomSerializer
{
    public override object Serialize(IDesignerSerializationManager manager, object value)
    {
        for (int index = 0; manager.Context[index] != null; index++)
        {
            StatementContext context = manager.Context[index] as StatementContext;
            if (context != null)
            {
                foreach (DictionaryEntry dictionaryEntry in context.StatementCollection)
                {
                    CodeStatementCollection _statements = dictionaryEntry.Value as CodeStatementCollection;
                    if(_statements != null)
                    {
                        for (int i = 0; i < _statements.Count; i++)
                        {
                            CodeAssignStatement assign = _statements[i] as CodeAssignStatement;
                            if (assign != null)
                            {
                                CodeFieldReferenceExpression field = assign.Left as CodeFieldReferenceExpression;
                                if (field != null)
                                {
                                    CodeMethodReferenceExpression _ref = new CodeMethodReferenceExpression(
                                        new CodeThisReferenceExpression(),
                                        "MyMethod");
                                    CodeMethodInvokeExpression save = new CodeMethodInvokeExpression(_ref, new CodeExpression[0]);
                                    CodeExpressionStatement newSt = new CodeExpressionStatement(save);
                                    _statements.Insert(i, newSt);
                                    i += 1;
                                }
                            }
                        }
                    }
                }
            }
        }

        CodeDomSerializer serializer = (CodeDomSerializer)manager.GetSerializer(typeof(UserControl).BaseType, typeof(CodeDomSerializer));
        object return_value = serializer.Serialize(manager, value);

        return return_value;
    }
}

不幸的是,这就是我得到的结果

    this.ctrl1 = new UserControl();
    this.ctrl2 = new UserControl();
    this.SuspendLayout();
    MyMethod(); // <---- call of my method
    .................................

有人重新组织CodeDom表达式,使InitializeComponent方法如下所示:

  1. 字段初始化
  2. SuspendLayout
  3. 设置初始化字段的属性
  4. 向Controls集合添加字段
  5. 设置容器的属性
  6. ResumeLayout
  7. 我有办法改变它吗?

0 个答案:

没有答案