private static void SelectWizard(IComponent wizardControl, IDesignerHost host)
 {
     if (wizardControl == null)
     {
         return;
     }
     if (host == null)
     {
         return;
     }
     while (true)
     {
         WizardDesigner designer = (WizardDesigner) host.GetDesigner(wizardControl);
         if (designer == null)
         {
             return;
         }
         ISelectionService service = (ISelectionService) host.GetService(typeof (ISelectionService));
         if (service == null)
         {
             return;
         }
         object[] components = new object[] {wizardControl};
         service.SetSelectedComponents(components, SelectionTypes.Replace);
         return;
     }
 }
 protected override void OnHandleCreated(EventArgs e)
 {
     base.OnHandleCreated(e);
     if (DesignMode && Site != null)
     {
         designerHost = Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
         var designer = (ControlDesigner)designerHost?.GetDesigner(this);
         designer?.Verbs?.Add(new DesignerVerb("Preview with dummy data", (o, a) =>
         {
             //Some logic to add dummy rows, just for example
             this.Rows.Clear();
             if (Columns.Count > 0)
             {
                 var values = Columns.Cast <DataGridViewColumn>()
                              .Select(x => GetDummyData(x)).ToArray();
                 for (int i = 0; i < 2; i++)
                 {
                     Rows.Add(values);
                 }
             }
         }));
         designer?.Verbs?.Add(new DesignerVerb("Clear data", (o, a) =>
         {
             this.Rows.Clear();
         }));
     }
 }
 protected override void OnHandleCreated(EventArgs e)
 {
     base.OnHandleCreated(e);
     if (DesignMode && Site != null)
     {
         designerHost    = Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
         behaviorService = designerHost?.GetService(typeof(BehaviorService)) as BehaviorService;
         var designer = designerHost?.GetDesigner(this) as ControlDesigner;
         if (designer != null)
         {
             var adorner = new Adorner();
             behaviorService.Adorners.Insert(0, adorner);
             adorner.Glyphs.Add(new MyTLPGlypg(behaviorService, this));
         }
     }
 }
Beispiel #4
0
 protected override void OnHandleCreated(EventArgs e)
 {
     base.OnHandleCreated(e);
     if (DesignMode && Site != null)
     {
         designerHost = Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
         var designer = (ControlDesigner)designerHost?.GetDesigner(this);
         designer?.Verbs?.Add(new DesignerVerb("Preview with dummy data", (o, a) =>
         {
             //Some logic to add dummy rows, just for example
             this.Rows.Clear();
             if (Columns.Count > 0)
             {
                 this.Rows.Add(2);
             }
         }));
         designer?.Verbs?.Add(new DesignerVerb("Clear data", (o, a) =>
         {
             this.Rows.Clear();
         }));
     }
 }
Beispiel #5
0
        /// <summary>
        ///  Serializes the given object into a CodeDom object.
        /// </summary>
        public override object Serialize(IDesignerSerializationManager manager, object value)
        {
            if (manager is null || value is null)
            {
                throw new ArgumentNullException(manager is null ? "manager" : "value");
            }

            // Find our base class's serializer.
            CodeDomSerializer serializer = (CodeDomSerializer)manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer));

            if (serializer is null)
            {
                Debug.Fail("Unable to find a CodeDom serializer for 'Component'.  Has someone tampered with the serialization providers?");

                return(null);
            }

            // Now ask it to serializer
            object retVal = serializer.Serialize(manager, value);
            InheritanceAttribute inheritanceAttribute = (InheritanceAttribute)TypeDescriptor.GetAttributes(value)[typeof(InheritanceAttribute)];
            InheritanceLevel     inheritanceLevel     = InheritanceLevel.NotInherited;

            if (inheritanceAttribute != null)
            {
                inheritanceLevel = inheritanceAttribute.InheritanceLevel;
            }

            if (inheritanceLevel != InheritanceLevel.InheritedReadOnly)
            {
                // Next, see if we are in localization mode.  If we are, and if we can get
                // to a ResourceManager through the service provider, then emit the hierarchy information for
                // this object.  There is a small fragile assumption here:  The resource manager is demand
                // created, so if all of the properties of this control had default values it is possible
                // there will be no resource manager for us.  I'm letting that slip a bit, however, because
                // for Control classes, we always emit at least the location / size information for the
                // control.
                IDesignerHost host = (IDesignerHost)manager.GetService(typeof(IDesignerHost));

                if (host != null)
                {
                    PropertyDescriptor prop = TypeDescriptor.GetProperties(host.RootComponent)["Localizable"];

                    if (prop != null && prop.PropertyType == typeof(bool) && ((bool)prop.GetValue(host.RootComponent)))
                    {
                        SerializeControlHierarchy(manager, host, value);
                    }
                }

                CodeStatementCollection csCollection = retVal as CodeStatementCollection;

                if (csCollection != null)
                {
                    Control control = (Control)value;

                    // Serialize a suspend / resume pair.  We always serialize this
                    // for the root component
                    if ((host != null && control == host.RootComponent) || HasSitedNonReadonlyChildren(control))
                    {
                        SerializeSuspendLayout(manager, csCollection, value);
                        SerializeResumeLayout(manager, csCollection, value);
                        ControlDesigner controlDesigner = host.GetDesigner(control) as ControlDesigner;

                        if (HasAutoSizedChildren(control) || (controlDesigner != null && controlDesigner.SerializePerformLayout))
                        {
                            SerializePerformLayout(manager, csCollection, value);
                        }
                    }

                    // And now serialize the correct z-order relationships for the controls.  We only need to
                    // do this if there are controls in the collection that are inherited.
                    if (HasMixedInheritedChildren(control))
                    {
                        SerializeZOrder(manager, csCollection, control);
                    }
                }
            }

            return(retVal);
        }
Beispiel #6
0
        protected void EnsureVerbs()
        {
            bool flag = false;

            if ((this._currentVerbs == null) && (this._serviceProvider != null))
            {
                Hashtable hashtable = null;
                if (this._selectionService == null)
                {
                    this._selectionService = this.GetService(typeof(ISelectionService)) as ISelectionService;
                    if (this._selectionService != null)
                    {
                        this._selectionService.SelectionChanging += new EventHandler(this.OnSelectionChanging);
                    }
                }
                int capacity = 0;
                DesignerVerbCollection verbs  = null;
                DesignerVerbCollection verbs2 = new DesignerVerbCollection();
                IDesignerHost          host   = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
                if (((this._selectionService != null) && (host != null)) && (this._selectionService.SelectionCount == 1))
                {
                    object primarySelection = this._selectionService.PrimarySelection;
                    if ((primarySelection is IComponent) && !TypeDescriptor.GetAttributes(primarySelection).Contains(InheritanceAttribute.InheritedReadOnly))
                    {
                        flag = primarySelection == host.RootComponent;
                        IDesigner designer = host.GetDesigner((IComponent)primarySelection);
                        if (designer != null)
                        {
                            verbs = designer.Verbs;
                            if (verbs != null)
                            {
                                capacity            += verbs.Count;
                                this._verbSourceType = primarySelection.GetType();
                            }
                            else
                            {
                                this._verbSourceType = null;
                            }
                        }
                        DesignerActionService service = this.GetService(typeof(DesignerActionService)) as DesignerActionService;
                        if (service != null)
                        {
                            DesignerActionListCollection componentActions = service.GetComponentActions(primarySelection as IComponent);
                            if (componentActions != null)
                            {
                                foreach (DesignerActionList list2 in componentActions)
                                {
                                    DesignerActionItemCollection sortedActionItems = list2.GetSortedActionItems();
                                    if (sortedActionItems != null)
                                    {
                                        for (int j = 0; j < sortedActionItems.Count; j++)
                                        {
                                            DesignerActionMethodItem item = sortedActionItems[j] as DesignerActionMethodItem;
                                            if ((item != null) && item.IncludeAsDesignerVerb)
                                            {
                                                EventHandler handler = new EventHandler(item.Invoke);
                                                DesignerVerb verb    = new DesignerVerb(item.DisplayName, handler);
                                                verbs2.Add(verb);
                                                capacity++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (flag && (this._globalVerbs == null))
                {
                    flag = false;
                }
                if (flag)
                {
                    capacity += this._globalVerbs.Count;
                }
                hashtable = new Hashtable(capacity, StringComparer.OrdinalIgnoreCase);
                ArrayList list = new ArrayList(capacity);
                if (flag)
                {
                    for (int k = 0; k < this._globalVerbs.Count; k++)
                    {
                        string text = ((DesignerVerb)this._globalVerbs[k]).Text;
                        hashtable[text] = list.Add(this._globalVerbs[k]);
                    }
                }
                if (verbs2.Count > 0)
                {
                    for (int m = 0; m < verbs2.Count; m++)
                    {
                        string str2 = verbs2[m].Text;
                        hashtable[str2] = list.Add(verbs2[m]);
                    }
                }
                if ((verbs != null) && (verbs.Count > 0))
                {
                    for (int n = 0; n < verbs.Count; n++)
                    {
                        string str3 = verbs[n].Text;
                        hashtable[str3] = list.Add(verbs[n]);
                    }
                }
                DesignerVerb[] verbArray = new DesignerVerb[hashtable.Count];
                int            index     = 0;
                for (int i = 0; i < list.Count; i++)
                {
                    DesignerVerb verb2 = (DesignerVerb)list[i];
                    string       str4  = verb2.Text;
                    if (((int)hashtable[str4]) == i)
                    {
                        verbArray[index] = verb2;
                        index++;
                    }
                }
                this._currentVerbs = new DesignerVerbCollection(verbArray);
            }
        }
 private string[] GetControlDataFieldNames()
 {
     if (this._dataFields == null)
     {
         ITypeDescriptorContext   context = this.editor.Context;
         IDataSourceFieldSchema[] fields  = null;
         IDataSourceViewSchema    dataSourceViewSchema = null;
         if ((context != null) && (context.Instance != null))
         {
             System.Web.UI.Control instance = context.Instance as System.Web.UI.Control;
             if (instance != null)
             {
                 ISite site = instance.Site;
                 if (site != null)
                 {
                     IDesignerHost host = (IDesignerHost)site.GetService(typeof(IDesignerHost));
                     if (host != null)
                     {
                         DataBoundControlDesigner designer = host.GetDesigner(instance) as DataBoundControlDesigner;
                         if (designer != null)
                         {
                             DesignerDataSourceView designerView = designer.DesignerView;
                             if (designerView != null)
                             {
                                 try
                                 {
                                     dataSourceViewSchema = designerView.Schema;
                                 }
                                 catch (Exception exception)
                                 {
                                     IComponentDesignerDebugService service = (IComponentDesignerDebugService)site.GetService(typeof(IComponentDesignerDebugService));
                                     if (service != null)
                                     {
                                         service.Fail(System.Design.SR.GetString("DataSource_DebugService_FailedCall", new object[] { "DesignerDataSourceView.Schema", exception.Message }));
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             else
             {
                 IDataSourceViewSchemaAccessor accessor = context.Instance as IDataSourceViewSchemaAccessor;
                 if (accessor != null)
                 {
                     dataSourceViewSchema = accessor.DataSourceViewSchema as IDataSourceViewSchema;
                 }
             }
         }
         if (dataSourceViewSchema != null)
         {
             fields = dataSourceViewSchema.GetFields();
             if (fields != null)
             {
                 int length = fields.Length;
                 this._dataFields = new string[length];
                 for (int i = 0; i < length; i++)
                 {
                     this._dataFields[i] = fields[i].Name;
                 }
             }
         }
     }
     return(this._dataFields);
 }
        /// <summary>
        /// 窗体初始化
        /// </summary>
        void CustomInitialize()
        {
            #region 添加ToolBox

            string fileName = Application.StartupPath + @"\..\data\SharpDevelopControlLibrary.xml";
            ComponentLibraryLoader componentLibraryLoader = new ComponentLibraryLoader();
            componentLibraryLoader.LoadToolComponentLibrary(fileName);

            Guanjinke.Windows.Forms.ToolBox toolBox = new Guanjinke.Windows.Forms.ToolBox {
                Dock = DockStyle.Fill
            };

            foreach (Category category in componentLibraryLoader.Categories)
            {
                if (category.IsEnabled)
                {
                    Guanjinke.Windows.Forms.ToolBoxCategory cate = new Guanjinke.Windows.Forms.ToolBoxCategory();
                    cate.ImageIndex = -1;
                    cate.IsOpen     = false;
                    cate.Name       = category.Name;
                    cate.Parent     = null;

                    Guanjinke.Windows.Forms.ToolBoxItem item = new Guanjinke.Windows.Forms.ToolBoxItem();
                    item.Tag    = null;
                    item.Name   = "<Pointer>";
                    item.Parent = null;
                    cate.Items.Add(item);

                    foreach (ToolComponent component in category.ToolComponents)
                    {
                        item = new Guanjinke.Windows.Forms.ToolBoxItem();

                        System.Drawing.Design.ToolboxItem toolboxItem = new System.Drawing.Design.ToolboxItem();
                        toolboxItem.TypeName    = component.FullName;
                        toolboxItem.Bitmap      = componentLibraryLoader.GetIcon(component);
                        toolboxItem.DisplayName = component.Name;
                        Assembly asm = component.LoadAssembly();
                        toolboxItem.AssemblyName = asm.GetName();

                        item.Image  = toolboxItem.Bitmap;
                        item.Tag    = toolboxItem;
                        item.Name   = component.Name;
                        item.Parent = null;

                        cate.Items.Add(item);
                    }

                    toolBox.Categories.Add(cate);
                }
            }

            pnlToolBox.Controls.Add(toolBox);//左边panel添加控件

            #endregion

            #region 添加PropertyPad

            _propertyGrid = new PropertyGrid {
                Dock = DockStyle.Fill
            };
            pnlPropertyGrid.Controls.Add(_propertyGrid);//右边属性表

            #endregion


            #region 添加 "服务" 、 "设计器" 及 "Code"窗口

            ServiceContainer serviceContainer = new ServiceContainer();
            serviceContainer.AddService(typeof(System.ComponentModel.Design.IDesignerEventService), new DesignerEventService());
            serviceContainer.AddService(typeof(System.ComponentModel.Design.Serialization.INameCreationService), new NameCreationService());
            _toolboxService = new CustomToolboxService();
            serviceContainer.AddService(typeof(IToolboxService), _toolboxService);

            DesignSurface surface = new DesignSurface(serviceContainer);
            _host = (IDesignerHost)surface.GetService(typeof(IDesignerHost));

            serviceContainer.AddService(typeof(System.ComponentModel.Design.IEventBindingService), new ICSharpCode.FormsDesigner.Services.EventBindingService(surface));

            _menuCommandService = new MenuCommandService(surface);
            serviceContainer.AddService(typeof(IMenuCommandService), _menuCommandService);

            //surface.BeginLoad(typeof(Form));
            _CodeDomHostLoader = new Loader.CodeDomHostLoader();
            surface.BeginLoad(_CodeDomHostLoader);

            Control designerContorl = (Control)surface.View;


            designerContorl.BackColor = Color.Aqua;
            designerContorl.Dock      = DockStyle.Fill;
            //获取root组件
            rootComponent = (Form)((IDesignerHost)this._host).RootComponent;

            rootComponent.FormBorderStyle = FormBorderStyle.None;


            #region 初始化窗体大小

            //- set the Size
            PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(designerContorl);
            //- Sets a PropertyDescriptor to the specific property.
            PropertyDescriptor pdS = pdc.Find("Size", false);
            if (null != pdS)
            {
                pdS.SetValue(_host.RootComponent, new Size(800, 480));
            }
            #endregion

            tpDesign.Controls.Add(designerContorl);//窗体


            _textEditor = new TextEditorControl
            {
                IsReadOnly = true,
                Dock       = DockStyle.Fill,
                Document   = { HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("C#") }
            }; //代码编辑器
            tpCode.Controls.Add(_textEditor);

            #endregion

            _propertyGrid.SelectedObject = surface.ComponentContainer.Components[0];
            SetAlignMenuEnabled(false);


            _propertyGrid.Site = (new IDEContainer(_host)).CreateSite(_propertyGrid);
            _propertyGrid.PropertyTabs.AddTabType(typeof(System.Windows.Forms.Design.EventsTab), PropertyTabScope.Document);

            #region 事件响应

            // 选中项改变时的事件
            _selectionService = surface.GetService(typeof(ISelectionService)) as ISelectionService;//获取surface中的SelectionService
            _selectionService.SelectionChanged += new EventHandler(selectionService_SelectionChanged);

            // 增/删/重命名组件的事件
            IComponentChangeService componentChangeService = (IComponentChangeService)surface.GetService(typeof(IComponentChangeService));
            componentChangeService.ComponentAdded   += ComponentListChanged;
            componentChangeService.ComponentRemoved += ComponentListChanged;
            componentChangeService.ComponentRename  += ComponentListChanged;
            _host.TransactionClosed += new DesignerTransactionCloseEventHandler(TransactionClosed);

            // 选中不同的工具条项目
            toolBox.SelectedItemChanged += delegate(object sender, Guanjinke.Windows.Forms.ToolBoxItem newItem)
            {
                _toolboxService.SetSelectedToolboxItem(newItem.Tag as System.Drawing.Design.ToolboxItem);
            };

            // 双击工具栏项目时增加到设计器中
            toolBox.ItemDoubleClicked += delegate(object sender, Guanjinke.Windows.Forms.ToolBoxItem newItem)
            {
                System.Drawing.Design.ToolboxItem toolboxItem = newItem.Tag as System.Drawing.Design.ToolboxItem;
                if (null != toolboxItem)
                {
                    IToolboxUser toolboxUser = _host.GetDesigner(_host.RootComponent as IComponent) as IToolboxUser;
                    if (null != toolboxUser)
                    {
                        toolboxUser.ToolPicked(toolboxItem);
                    }
                }
            };

            // 拖动工具栏项目的支持代码
            toolBox.ItemDragStart += delegate(object sender, Guanjinke.Windows.Forms.ToolBoxItem newItem)
            {
                System.Drawing.Design.ToolboxItem toolboxItem = newItem.Tag as System.Drawing.Design.ToolboxItem;
                if (null != toolboxItem)
                {
                    DataObject dataObject = ((IToolboxService)_toolboxService).SerializeToolboxItem(toolboxItem) as DataObject;
                    toolBox.DoDragDrop(dataObject, DragDropEffects.Copy);
                }
            };

            _toolboxService.ResetToolboxItem += delegate
            {
                toolBox.ResetSelection();
            };


            #endregion

            tsmiDelete.ShortcutKeys    = Keys.Delete;
            tsmiSelectAll.ShortcutKeys = Keys.Control | Keys.A;

            cmbControls.Sorted    = true;
            cmbControls.DrawMode  = DrawMode.OwnerDrawFixed;
            cmbControls.DrawItem += new DrawItemEventHandler(cmbControls_DrawItem);
            UpdateComboBox();

            #region 串口加载

            foreach (string com in System.IO.Ports.SerialPort.GetPortNames())
            {
                this.comPortName.Items.Add(com);
            }
            comParity.SelectedIndex = 0;
            if (comPortName.Items.Count > 0)
            {
                comPortName.SelectedIndex = 0;
            }

            #endregion
        }
Beispiel #9
0
        //utility, gets a root designer from an IDesignerHost and calls IsSupportedBy (object) on it
        public virtual bool IsSupportedBy(IDesignerHost host)
        {
            if (host == null)
                throw new ArgumentException ("IDesignerHost must not be null.");
            IComponent comp = host.RootComponent;
            if (comp == null)
                throw new ArgumentException ("Host does not have a root component.");
            IDesigner des = host.GetDesigner (comp);
            if (des == null)
                throw new ArgumentException ("Host does not have a root designer.");

            return IsSupportedBy (des);
        }
 private static Rectangle GetPaintingBounds(IDesignerHost designerHost, ToolStripItem item)
 {
     Rectangle empty = Rectangle.Empty;
     ToolStripItemDesigner designer = designerHost.GetDesigner(item) as ToolStripItemDesigner;
     if (designer != null)
     {
         empty = designer.GetGlyphBounds();
         ToolStripDesignerUtils.GetAdjustedBounds(item, ref empty);
         empty.Inflate(1, 1);
         empty.Width--;
         empty.Height--;
     }
     return empty;
 }
 private static ArrayList SerializeAttributes(object obj, IDesignerHost host, string prefix, ObjectPersistData persistData, string filter, bool topLevelInDesigner)
 {
     ArrayList list = new ArrayList();
     SerializeAttributesRecursive(obj, host, prefix, persistData, filter, list, null, null, topLevelInDesigner);
     if (persistData != null)
     {
         foreach (PropertyEntry entry in persistData.AllPropertyEntries)
         {
             BoundPropertyEntry entry2 = entry as BoundPropertyEntry;
             if ((entry2 != null) && !entry2.Generated)
             {
                 string[] strArray = entry2.Name.Split(new char[] { '.' });
                 if (strArray.Length > 1)
                 {
                     object component = obj;
                     foreach (string str in strArray)
                     {
                         PropertyDescriptor descriptor = TypeDescriptor.GetProperties(component)[str];
                         if (descriptor == null)
                         {
                             break;
                         }
                         PersistenceModeAttribute attribute = descriptor.Attributes[typeof(PersistenceModeAttribute)] as PersistenceModeAttribute;
                         if (attribute != PersistenceModeAttribute.Attribute)
                         {
                             string propValue = string.IsNullOrEmpty(entry2.ExpressionPrefix) ? entry2.Expression : (entry2.ExpressionPrefix + ":" + entry2.Expression);
                             string z = GetPersistValue(TypeDescriptor.GetProperties(entry2.PropertyInfo.DeclaringType)[entry2.PropertyInfo.Name], entry2.Type, propValue, string.IsNullOrEmpty(entry2.ExpressionPrefix) ? BindingType.Data : BindingType.Expression, topLevelInDesigner);
                             list.Add(new Triplet(entry2.Filter, ConvertObjectModelToPersistName(entry2.Name), z));
                             break;
                         }
                         component = descriptor.GetValue(component);
                     }
                 }
             }
         }
     }
     if (obj is Control)
     {
         System.Web.UI.AttributeCollection attributes = null;
         if (obj is WebControl)
         {
             attributes = ((WebControl) obj).Attributes;
         }
         else if (obj is HtmlControl)
         {
             attributes = ((HtmlControl) obj).Attributes;
         }
         else if (obj is UserControl)
         {
             attributes = ((UserControl) obj).Attributes;
         }
         if (attributes != null)
         {
             foreach (string str4 in attributes.Keys)
             {
                 string str5 = attributes[str4];
                 bool flag = false;
                 if (str5 != null)
                 {
                     object obj3;
                     bool flag2 = false;
                     string propName = ConvertPersistToObjectModelName(str4);
                     PropertyDescriptor descriptor2 = ControlDesigner.GetComplexProperty(obj, propName, out obj3);
                     if ((descriptor2 != null) && !descriptor2.IsReadOnly)
                     {
                         flag2 = true;
                     }
                     if (!flag2)
                     {
                         if (filter.Length == 0)
                         {
                             flag = true;
                         }
                         else
                         {
                             PropertyEntry filteredProperty = null;
                             if (persistData != null)
                             {
                                 filteredProperty = persistData.GetFilteredProperty(string.Empty, str4);
                             }
                             if (filteredProperty is SimplePropertyEntry)
                             {
                                 flag = !str5.Equals(((SimplePropertyEntry) filteredProperty).PersistedValue);
                             }
                             else if (filteredProperty is BoundPropertyEntry)
                             {
                                 string expression = ((BoundPropertyEntry) filteredProperty).Expression;
                                 string expressionPrefix = ((BoundPropertyEntry) filteredProperty).ExpressionPrefix;
                                 if (expressionPrefix.Length > 0)
                                 {
                                     expression = expressionPrefix + ":" + expression;
                                 }
                                 flag = !str5.Equals(expression);
                             }
                             else if (filteredProperty == null)
                             {
                                 flag = true;
                             }
                         }
                     }
                     if (flag)
                     {
                         list.Add(new Triplet(filter, str4, str5));
                     }
                 }
             }
         }
     }
     if (obj.GetType().Equals(typeof(UserControl)) && (persistData != null))
     {
         PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);
         foreach (PropertyEntry entry4 in persistData.AllPropertyEntries)
         {
             BoundPropertyEntry entry5 = entry4 as BoundPropertyEntry;
             if ((((entry5 != null) && !entry5.Generated) && (entry5.UseSetAttribute && string.Equals(entry4.Filter, filter, StringComparison.OrdinalIgnoreCase))) && (properties.Find(entry5.Name, false) == null))
             {
                 string str9 = entry5.Expression.Trim();
                 string str10 = entry5.ExpressionPrefix;
                 BindingType data = BindingType.Data;
                 if (!string.IsNullOrEmpty(str10))
                 {
                     str9 = str10 + ":" + str9;
                     data = BindingType.Expression;
                 }
                 string str11 = GetPersistValue(null, null, str9, data, topLevelInDesigner);
                 list.Add(new Triplet(entry5.Filter, ConvertObjectModelToPersistName(entry5.Name), str11));
             }
         }
     }
     if (persistData != null)
     {
         if (!string.IsNullOrEmpty(persistData.ResourceKey))
         {
             list.Add(new Triplet("meta", "resourceKey", persistData.ResourceKey));
         }
         if (!persistData.Localize)
         {
             list.Add(new Triplet("meta", "localize", "false"));
         }
         foreach (PropertyEntry entry6 in persistData.AllPropertyEntries)
         {
             if (string.Compare(entry6.Filter, filter, StringComparison.OrdinalIgnoreCase) != 0)
             {
                 if (entry6 is SimplePropertyEntry)
                 {
                     SimplePropertyEntry entry7 = (SimplePropertyEntry) entry6;
                     if (entry7.UseSetAttribute)
                     {
                         list.Add(new Triplet(entry6.Filter, ConvertObjectModelToPersistName(entry6.Name), entry7.Value.ToString()));
                     }
                 }
                 else if (entry6 is BoundPropertyEntry)
                 {
                     BoundPropertyEntry entry8 = (BoundPropertyEntry) entry6;
                     if (entry8.UseSetAttribute)
                     {
                         string str12 = ((BoundPropertyEntry) entry6).Expression;
                         string str13 = ((BoundPropertyEntry) entry6).ExpressionPrefix;
                         if (str13.Length > 0)
                         {
                             str12 = str13 + ":" + str12;
                         }
                         list.Add(new Triplet(entry6.Filter, ConvertObjectModelToPersistName(entry6.Name), str12));
                     }
                 }
             }
         }
     }
     if (((obj is Control) && (persistData != null)) && (host.GetDesigner((Control) obj) == null))
     {
         foreach (EventEntry entry9 in persistData.EventEntries)
         {
             list.Add(new Triplet(string.Empty, "On" + entry9.Name, entry9.HandlerMethodName));
         }
     }
     return list;
 }
Beispiel #12
0
        /// <summary>
        /// 粘贴
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void Paste(object sender, EventArgs args)
        {
            IDesignerSerializationService serialService = this.GetService(typeof(IDesignerSerializationService)) as IDesignerSerializationService;
            IDesignerHost           host          = GetService(typeof(IDesignerHost)) as IDesignerHost;
            ISelectionService       selection     = GetService(typeof(ISelectionService)) as ISelectionService;
            IComponentChangeService changeService = GetService(typeof(IComponentChangeService)) as IComponentChangeService;

            if (host == null || serialService == null || clipboardData == null)
            {
                return;
            }

            //从获取上次剪切/复制的数据并反序列化
            ICollection components = serialService.Deserialize(clipboardData);

            //如果当前选中的控件是容器控件则添加到容器中
            //否则添加到根设计器中
            if (components != null && components.Count > 0)
            {
                DesignerTransaction transaction = host.CreateTransaction("Paste");

                foreach (Component item in components)
                {
                    Control control = item as Control;
                    if (control == null)
                    {
                        continue;
                    }

                    //if (control is IDBColProperty)
                    //{
                    //    (control as IDBColProperty).DBColName = string.Empty;
                    //}

                    PropertyDescriptor parentProperty = TypeDescriptor.GetProperties(control)["Parent"];

                    //获取粘贴到的父容器
                    ParentControlDesigner parentDesigner = null;
                    if (selection != null && selection.PrimarySelection != null)
                    {
                        parentDesigner = host.GetDesigner((IComponent)selection.PrimarySelection) as ParentControlDesigner;
                    }

                    if (parentDesigner == null)
                    {
                        parentDesigner = host.GetDesigner(host.RootComponent) as DocumentDesigner;
                    }

                    if (parentDesigner != null && parentDesigner.CanParent(control))
                    {
                        //粘贴时粘贴到父容器中间
                        //control.Location = new Point(parentDesigner.Control.Width / 2 - control.Width / 2, parentDesigner.Control.Height / 2 - control.Height / 2);
                        parentProperty.SetValue(control, parentDesigner.Control);
                    }
                }

                clipboardData = null;
                transaction.Commit();
                ((IDisposable)transaction).Dispose();

                selection.SetSelectedComponents(components);
                this.GlobalInvoke(StandardCommands.BringToFront);
            }
        }
 internal static void GetAssociatedComponents(IComponent component, IDesignerHost host, ArrayList list)
 {
     if (host != null)
     {
         ComponentDesigner designer = host.GetDesigner(component) as ComponentDesigner;
         if (designer != null)
         {
             foreach (IComponent component2 in designer.AssociatedComponents)
             {
                 if (component2.Site != null)
                 {
                     list.Add(component2);
                     GetAssociatedComponents(component2, host, list);
                 }
             }
         }
     }
 }
Beispiel #14
0
        // Reminder: We set control.Parent so that it gets serialized for Undo/Redo
        //
        private void Paste(object sender, EventArgs args)
        {
            IDesignerSerializationService stateSerializer = GetService(typeof(IDesignerSerializationService)) as IDesignerSerializationService;
            ISelectionService             selection       = GetService(typeof(ISelectionService)) as ISelectionService;
            IDesignerHost           host          = GetService(typeof(IDesignerHost)) as IDesignerHost;
            IComponentChangeService changeService = GetService(typeof(IComponentChangeService)) as IComponentChangeService;

            if (host == null || stateSerializer == null)
            {
                return;
            }
            //
            // TODO: MWF X11 doesn't seem to support custom clipboard formats - bug #357642
            //
            // IDataObject dataObject = Clipboard.GetDataObject ();
            // byte[] data = dataObject == null ? null : dataObject.GetData (DT_DATA_FORMAT) as byte[];
            // if (data != null) {
            //  MemoryStream stream = new MemoryStream (data);
            //  stateSerializer.Deserialize (new BinaryFormatter().Deserialize (stream));
            // .....
            // }
            //
            if (_clipboard == null)
            {
                return;
            }

            DesignerTransaction transaction = host.CreateTransaction("Paste");
            ICollection         components  = stateSerializer.Deserialize(_clipboard);

            // Console.WriteLine ("Pasted components: ");
            // foreach (object c in components)
            //  Console.WriteLine (((IComponent)c).Site.Name);
            foreach (object component in components)
            {
                Control control = component as Control;
                if (control == null)
                {
                    continue;                     // pure Components are added to the ComponentTray by the DocumentDesigner
                }
                PropertyDescriptor parentProperty = TypeDescriptor.GetProperties(control)["Parent"];
                if (control.Parent != null)
                {
                    // Already parented during deserialization?
                    // In that case explicitly raise component changing/ed for the Parent property,
                    // so it get's cought by the UndoEngine
                    if (changeService != null)
                    {
                        changeService.OnComponentChanging(control, parentProperty);
                        changeService.OnComponentChanged(control, parentProperty, null, control.Parent);
                    }
                }
                else
                {
                    ParentControlDesigner parentDesigner = null;
                    if (selection != null && selection.PrimarySelection != null)
                    {
                        parentDesigner = host.GetDesigner((IComponent)selection.PrimarySelection) as ParentControlDesigner;
                    }
                    if (parentDesigner == null)
                    {
                        parentDesigner = host.GetDesigner(host.RootComponent) as DocumentDesigner;
                    }
                    if (parentDesigner != null && parentDesigner.CanParent(control))
                    {
                        parentProperty.SetValue(control, parentDesigner.Control);
                    }
                }
            }
            _clipboard = null;
            transaction.Commit();
            ((IDisposable)transaction).Dispose();
        }
Beispiel #15
0
        private void ToolsListBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            try
            {
                ListBox   LbSender           = sender as ListBox;
                Rectangle LastSelectedBounds = LbSender.GetItemRectangle(0);
                try
                {
                    LastSelectedBounds = LbSender.GetItemRectangle(SelectedIndex);
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }

                switch (e.KeyCode)
                {
                case Keys.Up: if (SelectedIndex > 0)
                    {
                        SelectedIndex--;                                                 // change selection
                        LbSender.SelectedIndex = SelectedIndex;
                        LbSender.Invalidate(LastSelectedBounds);                         // clear old highlight
                        LbSender.Invalidate(LbSender.GetItemRectangle(SelectedIndex));   // add new one
                    }
                    break;

                case Keys.Down: if (SelectedIndex + 1 < LbSender.Items.Count)
                    {
                        SelectedIndex++;                                                         // change selection
                        LbSender.SelectedIndex = SelectedIndex;
                        LbSender.Invalidate(LastSelectedBounds);                                 // clear old highlight
                        LbSender.Invalidate(LbSender.GetItemRectangle(SelectedIndex));           // add new one
                    }
                    break;

                case Keys.Enter:
                    if (DesignerHost == null)
                    {
                        MessageBox.Show("idh Null");
                    }

                    IToolboxUser TBU = DesignerHost.GetDesigner(DesignerHost.RootComponent as IComponent) as IToolboxUser;

                    if (TBU != null)
                    {
                        // Enter means place the tool with default location and default size.
                        TBU.ToolPicked((System.Drawing.Design.ToolboxItem)(LbSender.Items[SelectedIndex]));
                        LbSender.Invalidate(LastSelectedBounds);                                  // clear old highlight
                        LbSender.Invalidate(LbSender.GetItemRectangle(SelectedIndex));            // add new one
                    }

                    break;

                default:
                {
                    Console.WriteLine("Error: Not able to add");
                    break;
                }
                }                 // switch
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <include file='doc\DataFieldConverter.uex' path='docs/doc[@for="DataFieldConverter.GetStandardValues"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Gets the fields present within the selected data source if information about them is available.
        ///    </para>
        /// </devdoc>
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            object[]   names                 = null;
            String     dataMember            = null;
            bool       autoGenerateFields    = false;
            bool       autoGenerateFieldsSet = false;
            ObjectList objectList            = null;

            if (context != null)
            {
                ArrayList list = new ArrayList();

                PropertyDescriptorCollection props = null;

                IComponent component = context.Instance as IComponent;
                if (component is IDeviceSpecificChoiceDesigner)
                {
                    Object             owner = ((ChoicePropertyFilter)component).Owner;
                    PropertyDescriptor pd    =
                        ((ICustomTypeDescriptor)component).GetProperties()[_dataMemberPropertyName];
                    Debug.Assert(pd != null, "Cannot get DataMember");

                    if (owner is ObjectList)
                    {
                        autoGenerateFields    = ((ObjectList)owner).AutoGenerateFields;
                        autoGenerateFieldsSet = true;
                    }

                    component = ((IDeviceSpecificChoiceDesigner)component).UnderlyingControl;

                    // See if owner already has a DataMember
                    dataMember = (String)pd.GetValue(owner);
                    Debug.Assert(dataMember != null);
                    if (dataMember != null && dataMember.Length == 0)
                    {
                        // Get it from underlying object.
                        dataMember = (String)pd.GetValue(component);
                        Debug.Assert(dataMember != null);
                    }
                }

                if (component != null)
                {
                    objectList = component as ObjectList;

                    if (objectList != null)
                    {
                        foreach (ObjectListField field in objectList.Fields)
                        {
                            list.Add(field.Name);
                        }

                        if (!autoGenerateFieldsSet)
                        {
                            autoGenerateFields = objectList.AutoGenerateFields;
                        }
                    }

                    if (objectList == null || autoGenerateFields)
                    {
                        ISite componentSite = component.Site;
                        if (componentSite != null)
                        {
                            IDesignerHost designerHost = (IDesignerHost)componentSite.GetService(typeof(IDesignerHost));
                            if (designerHost != null)
                            {
                                IDesigner designer = designerHost.GetDesigner(component);

                                if (designer is IDataSourceProvider)
                                {
                                    IEnumerable dataSource = null;
                                    if (!String.IsNullOrEmpty(dataMember))
                                    {
                                        DataBindingCollection dataBindings =
                                            ((HtmlControlDesigner)designer).DataBindings;
                                        DataBinding binding = dataBindings[_dataSourcePropertyName];
                                        if (binding != null)
                                        {
                                            dataSource =
                                                DesignTimeData.GetSelectedDataSource(
                                                    component,
                                                    binding.Expression,
                                                    dataMember);
                                        }
                                    }
                                    else
                                    {
                                        dataSource =
                                            ((IDataSourceProvider)designer).GetResolvedSelectedDataSource();
                                    }

                                    if (dataSource != null)
                                    {
                                        props = DesignTimeData.GetDataFields(dataSource);
                                    }
                                }
                            }
                        }
                    }
                }

                if (props != null)
                {
                    foreach (PropertyDescriptor propDesc in props)
                    {
                        list.Add(propDesc.Name);
                    }
                }

                names = list.ToArray();
                Array.Sort(names);
            }
            return(new StandardValuesCollection(names));
        }
 internal static object CreateInstance(System.Type itemType, IDesignerHost host, string name)
 {
     object obj2 = null;
     if (typeof(IComponent).IsAssignableFrom(itemType) && (host != null))
     {
         obj2 = host.CreateComponent(itemType, name);
         if (host != null)
         {
             IComponentInitializer designer = host.GetDesigner((IComponent) obj2) as IComponentInitializer;
             if (designer != null)
             {
                 designer.InitializeNewComponent(null);
             }
         }
     }
     if (obj2 == null)
     {
         obj2 = TypeDescriptor.CreateInstance(host, itemType, null, null);
     }
     return obj2;
 }
Beispiel #18
0
        /// <summary>
        ///      Ensures that the verb list has been created.
        /// </summary>
        protected void EnsureVerbs()
        {
            // We apply global verbs only if the base component is the
            // currently selected object.
            //
            bool useGlobalVerbs = false;

            if (_currentVerbs is null && _serviceProvider != null)
            {
                Hashtable buildVerbs = null;
                ArrayList verbsOrder;

                if (_selectionService is null)
                {
                    _selectionService = GetService(typeof(ISelectionService)) as ISelectionService;

                    if (_selectionService != null)
                    {
                        _selectionService.SelectionChanging += new EventHandler(this.OnSelectionChanging);
                    }
                }

                int verbCount = 0;
                DesignerVerbCollection localVerbs          = null;
                DesignerVerbCollection designerActionVerbs = new DesignerVerbCollection(); // we instanciate this one here...
                IDesignerHost          designerHost        = GetService(typeof(IDesignerHost)) as IDesignerHost;

                if (_selectionService != null && designerHost != null && _selectionService.SelectionCount == 1)
                {
                    object selectedComponent = _selectionService.PrimarySelection;
                    if (selectedComponent is IComponent &&
                        !TypeDescriptor.GetAttributes(selectedComponent).Contains(InheritanceAttribute.InheritedReadOnly))
                    {
                        useGlobalVerbs = (selectedComponent == designerHost.RootComponent);

                        // LOCAL VERBS
                        IDesigner designer = designerHost.GetDesigner((IComponent)selectedComponent);
                        if (designer != null)
                        {
                            localVerbs = designer.Verbs;
                            if (localVerbs != null)
                            {
                                verbCount      += localVerbs.Count;
                                _verbSourceType = selectedComponent.GetType();
                            }
                            else
                            {
                                _verbSourceType = null;
                            }
                        }

                        // DesignerAction Verbs
                        DesignerActionService daSvc = GetService(typeof(DesignerActionService)) as DesignerActionService;
                        if (daSvc != null)
                        {
                            DesignerActionListCollection actionLists = daSvc.GetComponentActions(selectedComponent as IComponent);
                            if (actionLists != null)
                            {
                                foreach (DesignerActionList list in actionLists)
                                {
                                    DesignerActionItemCollection dai = list.GetSortedActionItems();
                                    if (dai != null)
                                    {
                                        for (int i = 0; i < dai.Count; i++)
                                        {
                                            DesignerActionMethodItem dami = dai[i] as DesignerActionMethodItem;
                                            if (dami != null && dami.IncludeAsDesignerVerb)
                                            {
                                                EventHandler handler = new EventHandler(dami.Invoke);
                                                DesignerVerb verb    = new DesignerVerb(dami.DisplayName, handler);
                                                designerActionVerbs.Add(verb);
                                                verbCount++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // GLOBAL VERBS
                if (useGlobalVerbs && _globalVerbs is null)
                {
                    useGlobalVerbs = false;
                }

                if (useGlobalVerbs)
                {
                    verbCount += _globalVerbs.Count;
                }

                // merge all
                buildVerbs = new Hashtable(verbCount, StringComparer.OrdinalIgnoreCase);
                verbsOrder = new ArrayList(verbCount);

                // PRIORITY ORDER FROM HIGH TO LOW: LOCAL VERBS - DESIGNERACTION VERBS - GLOBAL VERBS
                if (useGlobalVerbs)
                {
                    for (int i = 0; i < _globalVerbs.Count; i++)
                    {
                        string key = ((DesignerVerb)_globalVerbs[i]).Text;
                        buildVerbs[key] = verbsOrder.Add(_globalVerbs[i]);
                    }
                }

                if (designerActionVerbs.Count > 0)
                {
                    for (int i = 0; i < designerActionVerbs.Count; i++)
                    {
                        string key = designerActionVerbs[i].Text;
                        buildVerbs[key] = verbsOrder.Add(designerActionVerbs[i]);
                    }
                }

                if (localVerbs != null && localVerbs.Count > 0)
                {
                    for (int i = 0; i < localVerbs.Count; i++)
                    {
                        string key = localVerbs[i].Text;
                        buildVerbs[key] = verbsOrder.Add(localVerbs[i]);
                    }
                }

                // look for duplicate, prepare the result table
                DesignerVerb[] result = new DesignerVerb[buildVerbs.Count];
                int            j      = 0;
                for (int i = 0; i < verbsOrder.Count; i++)
                {
                    DesignerVerb value = (DesignerVerb)verbsOrder[i];
                    string       key   = value.Text;
                    if ((int)buildVerbs[key] == i)
                    { // there's not been a duplicate for this entry
                        result[j] = value;
                        j++;
                    }
                }

                _currentVerbs = new DesignerVerbCollection(result);
            }
        }
 private static string GetDirectives(IDesignerHost designerHost)
 {
     string registerDirectives = string.Empty;
     WebFormsReferenceManager referenceManager = null;
     if (designerHost.RootComponent != null)
     {
         WebFormsRootDesigner designer = designerHost.GetDesigner(designerHost.RootComponent) as WebFormsRootDesigner;
         if (designer != null)
         {
             referenceManager = designer.ReferenceManager;
         }
     }
     if (referenceManager == null)
     {
         IWebFormReferenceManager service = (IWebFormReferenceManager) designerHost.GetService(typeof(IWebFormReferenceManager));
         if (service != null)
         {
             registerDirectives = service.GetRegisterDirectives();
         }
         return registerDirectives;
     }
     StringBuilder builder = new StringBuilder();
     foreach (string str2 in referenceManager.GetRegisterDirectives())
     {
         builder.Append(str2);
     }
     return builder.ToString();
 }
Beispiel #20
0
 /// Get the designer for the given component and cast it as a designer filter.
 private IDesignerFilter GetDesignerFilter(IComponent component)
 {
     return(host.GetDesigner(component) as IDesignerFilter);
 }
		protected virtual IComponent[] CreateComponentsCore (IDesignerHost host, IDictionary defaultValues)
		{
			IComponent[] components = CreateComponentsCore (host);
			foreach (Component c in components) {
				IComponentInitializer initializer = host.GetDesigner (c) as IComponentInitializer;
				initializer.InitializeNewComponent (defaultValues);
			}
			return components;
		} 
Beispiel #22
0
 /// <summary>
 /// Returns the internal control designer with the specified index in the ControlDesigner.
 /// </summary>
 /// <param name="internalControlIndex">A specified index to select the internal control designer. This index is zero-based.</param>
 /// <returns>A ControlDesigner at the specified index.</returns>
 public override ControlDesigner InternalControlDesigner(int internalControlIndex) =>
 // Get the control designer for the requested indexed child control
 (_headerGroup != null) && (internalControlIndex == 0) ? (ControlDesigner)_designerHost.GetDesigner(_headerGroup.Panel) : null;
 protected override IComponent[] CreateComponentsCore(IDesignerHost host, IDictionary defaultValues)
 {
     Control control;
     IDesignerSerializationService service = (IDesignerSerializationService) host.GetService(typeof(IDesignerSerializationService));
     if (service == null)
     {
         return null;
     }
     ICollection is2 = service.Deserialize(this.serializationData);
     ArrayList list = new ArrayList();
     foreach (object obj2 in is2)
     {
         if ((obj2 != null) && (obj2 is IComponent))
         {
             list.Add(obj2);
         }
     }
     IComponent[] array = new IComponent[list.Count];
     list.CopyTo(array, 0);
     ArrayList components = null;
     if (defaultValues == null)
     {
         defaultValues = new Hashtable();
     }
     control = control = defaultValues["Parent"] as Control;
     if (control != null)
     {
         ParentControlDesigner designer = host.GetDesigner(control) as ParentControlDesigner;
         if (designer != null)
         {
             Rectangle empty = Rectangle.Empty;
             foreach (IComponent component in array)
             {
                 Control control2 = component as Control;
                 if (((control2 != null) && (control2 != control)) && (control2.Parent == null))
                 {
                     if (empty.IsEmpty)
                     {
                         empty = control2.Bounds;
                     }
                     else
                     {
                         empty = Rectangle.Union(empty, control2.Bounds);
                     }
                 }
             }
             defaultValues.Remove("Size");
             foreach (IComponent component2 in array)
             {
                 Control newChild = component2 as Control;
                 Form form = newChild as Form;
                 if (((newChild != null) && ((form == null) || !form.TopLevel)) && (newChild.Parent == null))
                 {
                     defaultValues["Offset"] = new Size(newChild.Bounds.X - empty.X, newChild.Bounds.Y - empty.Y);
                     designer.AddControl(newChild, defaultValues);
                 }
             }
         }
     }
     ComponentTray tray = (ComponentTray) host.GetService(typeof(ComponentTray));
     if (tray != null)
     {
         foreach (IComponent component3 in array)
         {
             ComponentTray.TrayControl trayControlFromComponent = tray.GetTrayControlFromComponent(component3);
             if (trayControlFromComponent != null)
             {
                 if (components == null)
                 {
                     components = new ArrayList();
                 }
                 components.Add(trayControlFromComponent);
             }
         }
         if (components != null)
         {
             tray.UpdatePastePositions(components);
         }
     }
     return array;
 }
Beispiel #24
0
        private void Initialize(ArrayList dragComponents, IDesignerHost host)
        {
            Control c = null;

            if ((dragComponents != null) && (dragComponents.Count > 0))
            {
                c = dragComponents[0] as Control;
            }
            Control   rootComponent = host.RootComponent as Control;
            Rectangle clipBounds    = new Rectangle(0, 0, rootComponent.ClientRectangle.Width, rootComponent.ClientRectangle.Height);

            clipBounds.Inflate(-1, -1);
            if (c != null)
            {
                this.dragOffset = this.behaviorService.ControlToAdornerWindow(c);
            }
            else
            {
                this.dragOffset = this.behaviorService.MapAdornerWindowPoint(rootComponent.Handle, Point.Empty);
                if ((rootComponent.Parent != null) && rootComponent.Parent.IsMirrored)
                {
                    this.dragOffset.Offset(-rootComponent.Width, 0);
                }
            }
            if (c != null)
            {
                ControlDesigner controlDesigner = host.GetDesigner(c) as ControlDesigner;
                bool            flag            = false;
                if (controlDesigner == null)
                {
                    controlDesigner = TypeDescriptor.CreateDesigner(c, typeof(IDesigner)) as ControlDesigner;
                    if (controlDesigner != null)
                    {
                        controlDesigner.ForceVisible = false;
                        controlDesigner.Initialize(c);
                        flag = true;
                    }
                }
                this.AddSnapLines(controlDesigner, this.targetHorizontalSnapLines, this.targetVerticalSnapLines, true, c != null);
                if (flag)
                {
                    controlDesigner.Dispose();
                }
            }
            foreach (IComponent component in host.Container.Components)
            {
                if (this.AddChildCompSnaplines(component, dragComponents, clipBounds, c))
                {
                    ControlDesigner designer = host.GetDesigner(component) as ControlDesigner;
                    if (designer != null)
                    {
                        if (this.AddControlSnaplinesWhenResizing(designer, component as Control, c))
                        {
                            this.AddSnapLines(designer, this.horizontalSnapLines, this.verticalSnapLines, false, c != null);
                        }
                        int num = designer.NumberOfInternalControlDesigners();
                        for (int i = 0; i < num; i++)
                        {
                            ControlDesigner designer3 = designer.InternalControlDesigner(i);
                            if (((designer3 != null) && this.AddChildCompSnaplines(designer3.Component, dragComponents, clipBounds, c)) && this.AddControlSnaplinesWhenResizing(designer3, designer3.Component as Control, c))
                            {
                                this.AddSnapLines(designer3, this.horizontalSnapLines, this.verticalSnapLines, false, c != null);
                            }
                        }
                    }
                }
            }
            this.verticalDistances   = new int[this.verticalSnapLines.Count];
            this.horizontalDistances = new int[this.horizontalSnapLines.Count];
        }
 internal static bool DeserializeDesignerStates(IDesignerHost designerHost, BinaryReader reader)
 {
     int num = reader.ReadInt32();
     bool flag = num != designerHost.Container.Components.Count;
     for (int i = 0; i < num; i++)
     {
         string str = reader.ReadString();
         int num3 = reader.ReadInt32();
         if (designerHost.Container.Components[str] != null)
         {
             ActivityDesigner designer = designerHost.GetDesigner(designerHost.Container.Components[str]) as ActivityDesigner;
             if (designer != null)
             {
                 ((IPersistUIState) designer).LoadViewState(reader);
             }
             else
             {
                 flag = true;
                 Stream baseStream = reader.BaseStream;
                 baseStream.Position += num3;
             }
         }
         else
         {
             flag = true;
             Stream stream2 = reader.BaseStream;
             stream2.Position += num3;
         }
     }
     return flag;
 }
Beispiel #26
0
        protected override object CreateInstance(WorkflowMarkupSerializationManager serializationManager, Type type)
        {
            Activity activity3;

            if (serializationManager == null)
            {
                throw new ArgumentNullException("serializationManager");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            object        obj2    = null;
            IDesignerHost service = serializationManager.GetService(typeof(IDesignerHost)) as IDesignerHost;
            XmlReader     reader  = serializationManager.WorkflowMarkupStack[typeof(XmlReader)] as XmlReader;

            if ((service == null) || (reader == null))
            {
                return(obj2);
            }
            string str = string.Empty;

            while (reader.MoveToNextAttribute() && !reader.LocalName.Equals("Name", StringComparison.Ordinal))
            {
            }
            if (reader.LocalName.Equals("Name", StringComparison.Ordinal) && reader.ReadAttributeValue())
            {
                str = reader.Value;
            }
            reader.MoveToElement();
            if (string.IsNullOrEmpty(str))
            {
                serializationManager.ReportError(SR.GetString("Error_LayoutSerializationAssociatedActivityNotFound", new object[] { reader.LocalName, "Name" }));
                return(obj2);
            }
            CompositeActivityDesigner designer = serializationManager.Context[typeof(CompositeActivityDesigner)] as CompositeActivityDesigner;

            if (designer != null)
            {
                CompositeActivity activity2 = designer.Activity as CompositeActivity;
                if (activity2 == null)
                {
                    goto Label_01D0;
                }
                activity3 = null;
                foreach (Activity activity4 in activity2.Activities)
                {
                    if (str.Equals(activity4.Name, StringComparison.Ordinal))
                    {
                        activity3 = activity4;
                        break;
                    }
                }
            }
            else
            {
                Activity rootComponent = service.RootComponent as Activity;
                if ((rootComponent != null) && !str.Equals(rootComponent.Name, StringComparison.Ordinal))
                {
                    foreach (IComponent component in service.Container.Components)
                    {
                        rootComponent = component as Activity;
                        if ((rootComponent != null) && str.Equals(rootComponent.Name, StringComparison.Ordinal))
                        {
                            break;
                        }
                    }
                }
                if (rootComponent != null)
                {
                    obj2 = service.GetDesigner(rootComponent);
                }
                goto Label_01D0;
            }
            if (activity3 != null)
            {
                obj2 = service.GetDesigner(activity3);
            }
Label_01D0:
            if (obj2 == null)
            {
                serializationManager.ReportError(SR.GetString("Error_LayoutSerializationActivityNotFound", new object[] { reader.LocalName, str, "Name" }));
            }
            return(obj2);
        }
        public static void InvalidateSelection(ArrayList originalSelComps, ToolStripItem nextSelection, IServiceProvider provider, bool shiftPressed)
        {
            // if we are not selecting a ToolStripItem then return (dont invalidate).
            if (nextSelection == null || provider == null)
            {
                return;
            }
            //InvalidateOriginal SelectedComponents.
            Region invalidateRegion        = null;
            Region itemRegion              = null;
            int    GLYPHBORDER             = 1;
            int    GLYPHINSET              = 2;
            ToolStripItemDesigner designer = null;
            bool templateNodeSelected      = false;

            try
            {
                Rectangle     invalidateBounds = Rectangle.Empty;
                IDesignerHost designerHost     = (IDesignerHost)provider.GetService(typeof(IDesignerHost));

                if (designerHost != null)
                {
                    foreach (Component comp in originalSelComps)
                    {
                        if (comp is ToolStripItem selItem)
                        {
                            if ((originalSelComps.Count > 1) ||
                                (originalSelComps.Count == 1 && selItem.GetCurrentParent() != nextSelection.GetCurrentParent()) ||
                                selItem is ToolStripSeparator || selItem is ToolStripControlHost || !selItem.IsOnDropDown || selItem.IsOnOverflow)
                            {
                                // finally Invalidate the selection rect ...
                                designer = designerHost.GetDesigner(selItem) as ToolStripItemDesigner;
                                if (designer != null)
                                {
                                    invalidateBounds = designer.GetGlyphBounds();
                                    GetAdjustedBounds(selItem, ref invalidateBounds);
                                    invalidateBounds.Inflate(GLYPHBORDER, GLYPHBORDER);

                                    if (invalidateRegion == null)
                                    {
                                        invalidateRegion = new Region(invalidateBounds);
                                        invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET);
                                        invalidateRegion.Exclude(invalidateBounds);
                                    }
                                    else
                                    {
                                        itemRegion = new Region(invalidateBounds);
                                        invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET);
                                        itemRegion.Exclude(invalidateBounds);
                                        invalidateRegion.Union(itemRegion);
                                    }
                                }
                            }
                        }
                    }
                }

                if (invalidateRegion != null || templateNodeSelected || shiftPressed)
                {
                    BehaviorService behaviorService = (BehaviorService)provider.GetService(typeof(BehaviorService));
                    if (behaviorService != null)
                    {
                        if (invalidateRegion != null)
                        {
                            behaviorService.Invalidate(invalidateRegion);
                        }

                        // When a ToolStripItem is PrimarySelection, the glyph bounds are not invalidated  through the SelectionManager so we have to do this.
                        designer = designerHost.GetDesigner(nextSelection) as ToolStripItemDesigner;
                        if (designer != null)
                        {
                            invalidateBounds = designer.GetGlyphBounds();
                            GetAdjustedBounds(nextSelection, ref invalidateBounds);
                            invalidateBounds.Inflate(GLYPHBORDER, GLYPHBORDER);
                            invalidateRegion = new Region(invalidateBounds);

                            invalidateBounds.Inflate(-GLYPHINSET, -GLYPHINSET);
                            invalidateRegion.Exclude(invalidateBounds);
                            behaviorService.Invalidate(invalidateRegion);
                        }
                    }
                }
            }
            finally
            {
                if (invalidateRegion != null)
                {
                    invalidateRegion.Dispose();
                }

                if (itemRegion != null)
                {
                    itemRegion.Dispose();
                }
            }
        }
            protected override IComponent[] CreateComponentsCore(IDesignerHost host, IDictionary defaultValues)
            {
                IDesignerSerializationService ds = (IDesignerSerializationService)host.GetService(typeof(IDesignerSerializationService));

                if (ds == null)
                {
                    return(null);
                }

                // Deserialize to components collection
                //
                ICollection objects    = ds.Deserialize(_serializationData);
                ArrayList   components = new ArrayList();

                foreach (object obj in objects)
                {
                    if (obj != null && obj is IComponent)
                    {
                        components.Add(obj);
                    }
                }

                IComponent[] componentsArray = new IComponent[components.Count];
                components.CopyTo(componentsArray, 0);

                ArrayList trayComponents = null;

                // Parent and locate each Control
                //
                if (defaultValues == null)
                {
                    defaultValues = new Hashtable();
                }
                Control parentControl = defaultValues["Parent"] as Control;

                if (parentControl != null)
                {
                    ParentControlDesigner parentControlDesigner = host.GetDesigner(parentControl) as ParentControlDesigner;
                    if (parentControlDesigner != null)
                    {
                        // Determine bounds of all controls
                        //
                        Rectangle bounds = Rectangle.Empty;

                        foreach (IComponent component in componentsArray)
                        {
                            Control childControl = component as Control;

                            if (childControl != null && childControl != parentControl && childControl.Parent == null)
                            {
                                if (bounds.IsEmpty)
                                {
                                    bounds = childControl.Bounds;
                                }
                                else
                                {
                                    bounds = Rectangle.Union(bounds, childControl.Bounds);
                                }
                            }
                        }

                        defaultValues.Remove("Size");    // don't care about the drag size
                        foreach (IComponent component in componentsArray)
                        {
                            Control childControl = component as Control;
                            Form    form         = childControl as Form;
                            if (childControl != null &&
                                !(form != null && form.TopLevel) && // Don't add top-level forms
                                childControl.Parent == null)
                            {
                                defaultValues["Offset"] = new Size(childControl.Bounds.X - bounds.X, childControl.Bounds.Y - bounds.Y);
                                parentControlDesigner.AddControl(childControl, defaultValues);
                            }
                        }
                    }
                }

                // VSWhidbey 516338 - When creating an item for the tray, template items will have
                // an old location stored in them, so they may show up on top of other items.
                // So we need to call UpdatePastePositions for each one to get the tray to
                // arrange them properly.
                //
                ComponentTray tray = (ComponentTray)host.GetService(typeof(ComponentTray));

                if (tray != null)
                {
                    foreach (IComponent component in componentsArray)
                    {
                        ComponentTray.TrayControl c = tray.GetTrayControlFromComponent(component);

                        if (c != null)
                        {
                            if (trayComponents == null)
                            {
                                trayComponents = new ArrayList();
                            }

                            trayComponents.Add(c);
                        }
                    }

                    if (trayComponents != null)
                    {
                        tray.UpdatePastePositions(trayComponents);
                    }
                }

                return(componentsArray);
            }
 /// <summary>
 /// Returns the internal control designer with the specified index in the ControlDesigner.
 /// </summary>
 /// <param name="internalControlIndex">A specified index to select the internal control designer. This index is zero-based.</param>
 /// <returns>A ControlDesigner at the specified index.</returns>
 public override ControlDesigner InternalControlDesigner(int internalControlIndex)
 {
     return((ControlDesigner)_designerHost.GetDesigner(_navigator.Pages[internalControlIndex]));
 }
Beispiel #30
0
        /// called to show the context menu for the selected component.
        public void ShowContextMenu(System.ComponentModel.Design.CommandID menuID, int x, int y)
        {
            ISelectionService selectionService = host.GetService(typeof(ISelectionService)) as ISelectionService;
            // get the primary component
            IComponent primarySelection = selectionService.PrimarySelection as IComponent;

            // if the he clicked on the same component again then just show the context
            // menu. otherwise, we have to throw away the previous
            // set of local menu items and create new ones for the newly
            // selected component
            if (lastSelectedComponent != primarySelection)
            {
                // remove all non-global menu items from the context menu
                ResetContextMenu();
                // get the designer
                IDesigner designer = host.GetDesigner(primarySelection);
                // not all controls need a desinger
                if (designer != null)
                {
                    // get designer's verbs
                    DesignerVerbCollection verbs = designer.Verbs;
                    foreach (DesignerVerb verb in verbs)
                    {
                        // add new menu items to the context menu
                        CreateAndAddLocalVerb(verb);
                    }
                }
            }
            // we only show designer context menus for controls

            Control comp = primarySelection as Control; //roman//

            if (comp == null)
            {
                comp = VisualPascalABC.VisualPABCSingleton.MainForm;
            }

            ToolStripMenuItem[] menuItems1 = new ToolStripMenuItem[VisualPascalABC.VisualPABCSingleton.MainForm.cm_Designer.Items.Count];
            ToolStripMenuItem[] menuItems2 = new ToolStripMenuItem[contextMenu.Items.Count];
            VisualPascalABC.VisualPABCSingleton.MainForm.cm_Designer.Items.CopyTo(menuItems1, 0);
            contextMenu.Items.CopyTo(menuItems2, 0);
            ContextMenuStrip menu = new ContextMenuStrip();

            menu.Items.AddRange(menuItems1);
            if (menuItems2.Length > 0)
            {
                menu.Items.Add(new ToolStripSeparator());
            }
            menu.Items.AddRange(menuItems2);
            Point pt = comp.PointToScreen(new Point(0, 0));

            menu.Show(comp, new Point(x - pt.X, y - pt.Y));

            /*Следующее делается по следующей причине:
             * почему то при menu.Items.AddRange(menuItems1); удаляются элементы из VisualPascalABC.Form1.Form1_object.cm_Designer,
             * аналогично для menu.Items.AddRange(menuItems2);
             */
            menu.Closed += delegate
            {
                VisualPascalABC.VisualPABCSingleton.MainForm.cm_Designer.Items.Clear();
                contextMenu.Items.Clear();
                VisualPascalABC.VisualPABCSingleton.MainForm.cm_Designer.Items.AddRange(menuItems1);
                contextMenu.Items.AddRange(menuItems2);
                return;
            };
            // keep the selected component for next time
            lastSelectedComponent = primarySelection;
        }
 protected override IComponent[] CreateComponentsCore(IDesignerHost host)
 {
     IComponent[] sourceArray = base.CreateComponentsCore(host);
     Control component = null;
     ControlDesigner parent = null;
     TabStrip strip = null;
     IComponentChangeService service = (IComponentChangeService) host.GetService(typeof(IComponentChangeService));
     if ((sourceArray.Length > 0) && (sourceArray[0] is TabStrip))
     {
         strip = sourceArray[0] as TabStrip;
         ITreeDesigner designer2 = host.GetDesigner(strip) as ITreeDesigner;
         parent = designer2.Parent as ControlDesigner;
         if (parent != null)
         {
             component = parent.Control;
         }
     }
     if (host != null)
     {
         TabPageSwitcher switcher = null;
         DesignerTransaction transaction = null;
         try
         {
             try
             {
                 transaction = host.CreateTransaction("add tabswitcher");
             }
             catch (CheckoutException exception)
             {
                 if (exception != CheckoutException.Canceled)
                 {
                     throw exception;
                 }
                 return sourceArray;
             }
             MemberDescriptor member = TypeDescriptor.GetProperties(parent)["Controls"];
             switcher = host.CreateComponent(typeof(TabPageSwitcher)) as TabPageSwitcher;
             if (service != null)
             {
                 service.OnComponentChanging(component, member);
                 service.OnComponentChanged(component, member, null, null);
             }
             Dictionary<string, object> properties = new Dictionary<string, object>();
             properties["Location"] = new Point(strip.Left, strip.Bottom + 3);
             properties["TabStrip"] = strip;
             this.SetProperties(switcher, properties, host);
         }
         finally
         {
             if (transaction != null)
             {
                 transaction.Commit();
             }
         }
         if (switcher != null)
         {
             IComponent[] destinationArray = new IComponent[sourceArray.Length + 1];
             Array.Copy(sourceArray, destinationArray, sourceArray.Length);
             destinationArray[destinationArray.Length - 1] = switcher;
             return destinationArray;
         }
     }
     return sourceArray;
 }
Beispiel #32
0
        private void RefreshSelectionMenuItem()
        {
            int index = -1;

            if (this.selectionMenuItem != null)
            {
                index = this.Items.IndexOf(this.selectionMenuItem);
                base.Groups["Selection"].Items.Remove(this.selectionMenuItem);
                this.Items.Remove(this.selectionMenuItem);
            }
            ArrayList         list    = new ArrayList();
            int               count   = 0;
            ISelectionService service = this.serviceProvider.GetService(typeof(ISelectionService)) as ISelectionService;
            IDesignerHost     host    = this.serviceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;

            if ((service != null) && (host != null))
            {
                IComponent rootComponent    = host.RootComponent;
                Control    primarySelection = service.PrimarySelection as Control;
                if (((primarySelection != null) && (rootComponent != null)) && (primarySelection != rootComponent))
                {
                    for (Control control2 = primarySelection.Parent; control2 != null; control2 = control2.Parent)
                    {
                        if (control2.Site != null)
                        {
                            list.Add(control2);
                            count++;
                        }
                        if (control2 == rootComponent)
                        {
                            break;
                        }
                    }
                }
                else if (service.PrimarySelection is ToolStripItem)
                {
                    ToolStripItem         component = service.PrimarySelection as ToolStripItem;
                    ToolStripItemDesigner designer  = host.GetDesigner(component) as ToolStripItemDesigner;
                    if (designer != null)
                    {
                        list  = designer.AddParentTree();
                        count = list.Count;
                    }
                }
            }
            if (count > 0)
            {
                this.selectionMenuItem = new ToolStripMenuItem();
                IUIService service2 = this.serviceProvider.GetService(typeof(IUIService)) as IUIService;
                if (service2 != null)
                {
                    this.selectionMenuItem.DropDown.Renderer = (ToolStripProfessionalRenderer)service2.Styles["VsRenderer"];
                    this.selectionMenuItem.DropDown.Font     = (Font)service2.Styles["DialogFont"];
                }
                this.selectionMenuItem.Text = System.Design.SR.GetString("ContextMenuSelect");
                foreach (Component component2 in list)
                {
                    ToolStripMenuItem item2 = new SelectToolStripMenuItem(component2, this.serviceProvider);
                    this.selectionMenuItem.DropDownItems.Add(item2);
                }
                base.Groups["Selection"].Items.Add(this.selectionMenuItem);
                if (index != -1)
                {
                    this.Items.Insert(index, this.selectionMenuItem);
                }
            }
        }
Beispiel #33
0
        public Control CreateControl(Type controlType, Size controlSize, Point controlLocation)
        {
            try {
                //- step.1
                //- get the IDesignerHost
                //- if we are not able to get it
                //- then rollback (return without do nothing)
                IDesignerHost host = GetIDesignerHost();
                if (null == host)
                {
                    return(null);
                }
                //- check if the root component has already been set
                //- if not so then rollback (return without do nothing)
                if (null == host.RootComponent)
                {
                    return(null);
                }
                //-
                //-
                //- step.2
                //- create a new component and initialize it via its designer
                //- if the component has not a designer
                //- then rollback (return without do nothing)
                //- else do the initialization
                IComponent newComp = host.CreateComponent(controlType);
                if (null == newComp)
                {
                    return(null);
                }
                IDesigner designer = host.GetDesigner(newComp);
                if (null == designer)
                {
                    return(null);
                }
                if (designer is IComponentInitializer)
                {
                    (( IComponentInitializer )designer).InitializeNewComponent(null);
                }
                //-
                //-
                //- step.3
                //- try to modify the Size/Location of the object just created
                PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(newComp);
                //- Sets a PropertyDescriptor to the specific property.
                PropertyDescriptor pdS = pdc.Find("Size", false);
                if (null != pdS)
                {
                    pdS.SetValue(newComp, controlSize);
                }
                PropertyDescriptor pdL = pdc.Find("Location", false);
                if (null != pdL)
                {
                    pdL.SetValue(newComp, controlLocation);
                }
                //-
                //-
                //- step.4
                //- commit the Creation Operation
                //- adding the control to the DesignSurface's root component
                //- and return the control just created to let further initializations
                (( Control )newComp).Parent = host.RootComponent as Control;
                return(newComp as Control);
            }//end_try
            catch (Exception exx) {
                Debug.WriteLine(exx.Message);
                if (null != exx.InnerException)
                {
                    Debug.WriteLine(exx.InnerException.Message);
                }

                throw;
            }//end_catch
        }
Beispiel #34
0
        public Control CreateControl(ReportUtils.ReportControlProperties reportControlProperties)
        {
            try
            {
                //- step.1
                //- get the IDesignerHost
                //- if we are not able to get it
                //- then rollback (return without do nothing)
                IDesignerHost host = GetIDesignerHost();
                if (null == host)
                {
                    return(null);
                }
                //- check if the root component has already been set
                //- if not so then rollback (return without do nothing)
                if (null == host.RootComponent)
                {
                    return(null);
                }
                //-
                //-
                //- step.2
                //- create a new component and initialize it via its designer
                //- if the component has not a designer
                //- then rollback (return without do nothing)
                //- else do the initialization
                //IComponent newComp = host.CreateComponent(typeof(ReportUtils.Type));
                //IComponent newComp = host.CreateComponent(Type.GetType(reportControlProperties.Type));

                IComponent newComp = host.CreateComponent(GetTypeFromSimpleName(reportControlProperties.Type));

                Type type = GetTypeFromSimpleName(reportControlProperties.Type);

                if (null == newComp)
                {
                    return(null);
                }
                IDesigner designer = host.GetDesigner(newComp);
                if (null == designer)
                {
                    return(null);
                }
                if (designer is IComponentInitializer)
                {
                    ((IComponentInitializer)designer).InitializeNewComponent(null);
                }
                //-
                //-
                //- step.3
                //- try to modify the Size/Location of the object just created
                PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(newComp);

                //- Sets a PropertyDescriptor to the specific property.
                PropertyDescriptor pdS = pdc.Find("Size", false);
                if (null != pdS)
                {
                    pdS.SetValue(newComp, (reportControlProperties.Size));
                }

                PropertyDescriptor pdName = pdc.Find("Name", false);
                if (null != pdName)
                {
                    pdName.SetValue(newComp, (reportControlProperties.Name));
                }

                PropertyDescriptor pdL = pdc.Find("Location", false);
                if (null != pdL)
                {
                    pdL.SetValue(newComp, new Point(reportControlProperties.Location._X, reportControlProperties.Location._Y));
                }
                PropertyDescriptor pdF = pdc.Find("Font", false);
                if (null != pdF)
                {
                    Font font = new Font(reportControlProperties.Font.FontFamily, reportControlProperties.Font.FontSize, reportControlProperties.Font.FontStyle);
                    pdF.SetValue(newComp, font);
                }
                PropertyDescriptor pdFc = pdc.Find("ForeColor", false);
                if (null != pdFc)
                {
                    Color color = Color.FromName(reportControlProperties.Font.FontColor);
                    if (!color.IsKnownColor)
                    {
                        color = ColorTranslator.FromHtml("#" + color.Name);
                    }
                    pdFc.SetValue(newComp, color);
                }

                PropertyDescriptor pdFBorder = pdc.Find("BorderStyle", false);
                if (null != pdFBorder)
                {
                    if (reportControlProperties.Border)
                    {
                        pdFBorder.SetValue(newComp, BorderStyle.FixedSingle);
                    }
                    else
                    {
                        pdFBorder.SetValue(newComp, BorderStyle.None);
                    }
                }

                PropertyDescriptor pdText = pdc.Find("Text", false);
                if (null != pdText)
                {
                    pdText.SetValue(newComp, reportControlProperties.Text);
                }

                if (type == typeof(PictureBox))
                {
                    PropertyDescriptor pdImageLocation = pdc.Find("ImageLocation", false);
                    if (null != pdImageLocation)
                    {
                        pdImageLocation.SetValue(newComp, reportControlProperties.ImageName);
                    }
                    pdImageLocation = pdc.Find("SizeMode", false);
                    if (null != pdImageLocation)
                    {
                        pdImageLocation.SetValue(newComp, PictureBoxSizeMode.Zoom);
                    }
                }

                PropertyDescriptor pdMultiLine = pdc.Find("Multiline", false);
                if (null != pdMultiLine)
                {
                    pdMultiLine.SetValue(newComp, reportControlProperties.MultiLine);
                }
                PropertyDescriptor pdTextAlign = pdc.Find("TextAlign", false);
                if (null != pdTextAlign)
                {
                    if (type == typeof(Label))
                    {
                        ContentAlignment c = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), reportControlProperties.TextAlign.ToString());
                        pdTextAlign.SetValue(newComp, c);
                    }
                }

                PropertyDescriptor pdTag = pdc.Find("Tag", false);
                if (null != pdTag)
                {
                    pdTag.SetValue(newComp, reportControlProperties.Binding);
                }

                if (type == typeof(TableLayoutPanel))
                {
                    PropertyDescriptor pdTableLayout = pdc.Find("RowCount", false);
                    if (null != pdTableLayout)
                    {
                        pdTableLayout.SetValue(newComp, reportControlProperties.RowsColumns._Rows);
                    }
                    pdTableLayout = pdc.Find("ColumnCount", false);
                    if (null != pdTableLayout)
                    {
                        pdTableLayout.SetValue(newComp, reportControlProperties.RowsColumns._Columns);
                    }
                    pdTableLayout = pdc.Find("CellBorderStyle", false);
                    if (null != pdTableLayout)
                    {
                        if (reportControlProperties.Border)
                        {
                            pdTableLayout.SetValue(newComp, DataGridViewAdvancedCellBorderStyle.Single);
                        }
                        else
                        {
                            pdTableLayout.SetValue(newComp, DataGridViewAdvancedCellBorderStyle.None);
                        }
                    }
                }
                if (type == typeof(IVL_ImagePanel))
                {
                    PropertyDescriptor pdTableLayout = pdc.Find("Images", false);
                    if (null != pdTableLayout)
                    {
                        pdTableLayout.SetValue(newComp, reportControlProperties.NumberOfImages);
                    }
                    pdTableLayout = pdc.Find("BorderStyle", false);
                    if (null != pdTableLayout)
                    {
                        pdTableLayout.SetValue(newComp, BorderStyle.FixedSingle);
                    }
                }
                //-
                //-
                //- step.4
                //- commit the Creation Operation
                //- adding the control to the DesignSurface's root component
                //- and return the control just created to let further initializations
                ((Control)newComp).Parent = host.RootComponent as Control;
                return(newComp as Control);
            }//end_try
            catch (Exception exx)
            {
                Debug.WriteLine(exx.Message);
                if (null != exx.InnerException)
                {
                    Debug.WriteLine(exx.InnerException.Message);
                }

                throw;
            }//end_catch
        }
 private void Initialize(ArrayList dragComponents, IDesignerHost host)
 {
     Control c = null;
     if ((dragComponents != null) && (dragComponents.Count > 0))
     {
         c = dragComponents[0] as Control;
     }
     Control rootComponent = host.RootComponent as Control;
     Rectangle clipBounds = new Rectangle(0, 0, rootComponent.ClientRectangle.Width, rootComponent.ClientRectangle.Height);
     clipBounds.Inflate(-1, -1);
     if (c != null)
     {
         this.dragOffset = this.behaviorService.ControlToAdornerWindow(c);
     }
     else
     {
         this.dragOffset = this.behaviorService.MapAdornerWindowPoint(rootComponent.Handle, Point.Empty);
         if ((rootComponent.Parent != null) && rootComponent.Parent.IsMirrored)
         {
             this.dragOffset.Offset(-rootComponent.Width, 0);
         }
     }
     if (c != null)
     {
         ControlDesigner controlDesigner = host.GetDesigner(c) as ControlDesigner;
         bool flag = false;
         if (controlDesigner == null)
         {
             controlDesigner = TypeDescriptor.CreateDesigner(c, typeof(IDesigner)) as ControlDesigner;
             if (controlDesigner != null)
             {
                 controlDesigner.ForceVisible = false;
                 controlDesigner.Initialize(c);
                 flag = true;
             }
         }
         this.AddSnapLines(controlDesigner, this.targetHorizontalSnapLines, this.targetVerticalSnapLines, true, c != null);
         if (flag)
         {
             controlDesigner.Dispose();
         }
     }
     foreach (IComponent component in host.Container.Components)
     {
         if (this.AddChildCompSnaplines(component, dragComponents, clipBounds, c))
         {
             ControlDesigner designer = host.GetDesigner(component) as ControlDesigner;
             if (designer != null)
             {
                 if (this.AddControlSnaplinesWhenResizing(designer, component as Control, c))
                 {
                     this.AddSnapLines(designer, this.horizontalSnapLines, this.verticalSnapLines, false, c != null);
                 }
                 int num = designer.NumberOfInternalControlDesigners();
                 for (int i = 0; i < num; i++)
                 {
                     ControlDesigner designer3 = designer.InternalControlDesigner(i);
                     if (((designer3 != null) && this.AddChildCompSnaplines(designer3.Component, dragComponents, clipBounds, c)) && this.AddControlSnaplinesWhenResizing(designer3, designer3.Component as Control, c))
                     {
                         this.AddSnapLines(designer3, this.horizontalSnapLines, this.verticalSnapLines, false, c != null);
                     }
                 }
             }
         }
     }
     this.verticalDistances = new int[this.verticalSnapLines.Count];
     this.horizontalDistances = new int[this.horizontalSnapLines.Count];
 }
Beispiel #36
0
 public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
 {
     object[] values = null;
     if (context != null)
     {
         IComponent instance = context.Instance as IComponent;
         if (instance != null)
         {
             ISite site = instance.Site;
             if (site != null)
             {
                 IDesignerHost host = (IDesignerHost)site.GetService(typeof(IDesignerHost));
                 if (host != null)
                 {
                     IDesigner dataBoundControlDesigner = host.GetDesigner(instance);
                     DesignerDataSourceView view        = this.GetView(dataBoundControlDesigner);
                     if (view != null)
                     {
                         IDataSourceViewSchema schema = null;
                         try
                         {
                             schema = view.Schema;
                         }
                         catch (Exception exception)
                         {
                             IComponentDesignerDebugService service = (IComponentDesignerDebugService)site.GetService(typeof(IComponentDesignerDebugService));
                             if (service != null)
                             {
                                 service.Fail(System.Design.SR.GetString("DataSource_DebugService_FailedCall", new object[] { "DesignerDataSourceView.Schema", exception.Message }));
                             }
                         }
                         if (schema != null)
                         {
                             IDataSourceFieldSchema[] fields = schema.GetFields();
                             if (fields != null)
                             {
                                 values = new object[fields.Length];
                                 for (int i = 0; i < fields.Length; i++)
                                 {
                                     values[i] = fields[i].Name;
                                 }
                             }
                         }
                     }
                     if (((values == null) && (dataBoundControlDesigner != null)) && (dataBoundControlDesigner is IDataSourceProvider))
                     {
                         IDataSourceProvider provider   = dataBoundControlDesigner as IDataSourceProvider;
                         IEnumerable         dataSource = null;
                         if (provider != null)
                         {
                             dataSource = provider.GetResolvedSelectedDataSource();
                         }
                         if (dataSource != null)
                         {
                             PropertyDescriptorCollection dataFields = DesignTimeData.GetDataFields(dataSource);
                             if (dataFields != null)
                             {
                                 ArrayList list = new ArrayList();
                                 foreach (PropertyDescriptor descriptor in dataFields)
                                 {
                                     list.Add(descriptor.Name);
                                 }
                                 values = list.ToArray();
                             }
                         }
                     }
                 }
             }
         }
     }
     return(new TypeConverter.StandardValuesCollection(values));
 }
 private static string GetTagName(Type type, IDesignerHost host)
 {
     string fullName = string.Empty;
     string tagPrefix = string.Empty;
     WebFormsReferenceManager referenceManager = null;
     if (host.RootComponent != null)
     {
         WebFormsRootDesigner designer = host.GetDesigner(host.RootComponent) as WebFormsRootDesigner;
         if (designer != null)
         {
             referenceManager = designer.ReferenceManager;
         }
     }
     if (referenceManager == null)
     {
         IWebFormReferenceManager service = (IWebFormReferenceManager) host.GetService(typeof(IWebFormReferenceManager));
         if (service != null)
         {
             tagPrefix = service.GetTagPrefix(type);
         }
     }
     else
     {
         tagPrefix = referenceManager.GetTagPrefix(type);
     }
     if (string.IsNullOrEmpty(tagPrefix))
     {
         tagPrefix = referenceManager.RegisterTagPrefix(type);
     }
     if ((tagPrefix != null) && (tagPrefix.Length != 0))
     {
         fullName = tagPrefix + ":" + type.Name;
     }
     if (fullName.Length == 0)
     {
         fullName = type.FullName;
     }
     return fullName;
 }
Beispiel #38
0
        /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponentsCore1"]/*' />
        /// <devdoc>
        ///     Creates objects from the type contained in this toolbox item.  If designerHost is non-null
        ///     this will also add them to the designer.
        /// </devdoc>
        protected virtual IComponent[] CreateComponentsCore(IDesignerHost host, IDictionary defaultValues) {
            IComponent[] components = CreateComponentsCore(host);

            if (host != null) {
                for (int i = 0; i < components.Length; i++) {
                    IComponentInitializer init = host.GetDesigner(components[i]) as IComponentInitializer;
                    if (init != null) {
                        bool removeComponent = true;
                        
                        try {
                            init.InitializeNewComponent(defaultValues);
                            removeComponent = false;

                        }
                        finally 
                        {
                            if (removeComponent) {
                                for (int index = 0; index < components.Length; index++) {
                                    host.DestroyComponent(components[index]);
                                }
                            }
                        }

                    }
                }
            }

            return components;
        }
        private void SetupBackstageTab(SuperTabControl backstageTab, IDesignerHost dh)
        {
            backstageTab.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            backstageTab.ControlBox.Visible = false;
            backstageTab.ItemPadding.Left = 6;
            backstageTab.ItemPadding.Right = 4;
            backstageTab.ItemPadding.Top = 4;
            backstageTab.ReorderTabsEnabled = false;
            try
            {
                backstageTab.SelectedTabFont = new System.Drawing.Font("Segoe UI", 9.75F);
            }
            catch { }
            backstageTab.SelectedTabIndex = 0;
            backstageTab.Size = new System.Drawing.Size(614, 315);
            backstageTab.TabAlignment = DevComponents.DotNetBar.eTabStripAlignment.Left;
            try
            {
                backstageTab.TabFont = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            }
            catch { }
            backstageTab.TabHorizontalSpacing = 16;
            backstageTab.TabStyle = DevComponents.DotNetBar.eSuperTabStyle.Office2010BackstageBlue;
            backstageTab.TabVerticalSpacing = 8;

            SuperTabControlDesigner tabDesigner = dh.GetDesigner(backstageTab) as SuperTabControlDesigner;
            if (tabDesigner != null)
            {
                ButtonItem button;
                // Save button
                button = tabDesigner.CreateButton();
                SetProperty(button, "Text", "Save");
                SetProperty(button, "KeyTips", "S");
                SetProperty(button, "Image", RibbonControlDesigner.LoadImage("Save16.png"));

                // Open
                button = tabDesigner.CreateButton();
                SetProperty(button, "Text", "Open");
                SetProperty(button, "KeyTips", "O");
                SetProperty(button, "Image", RibbonControlDesigner.LoadImage("Open.png"));

                // Close
                button = tabDesigner.CreateButton();
                SetProperty(button, "Text", "Close");
                SetProperty(button, "KeyTips", "C");
                SetProperty(button, "Image", RibbonControlDesigner.LoadImage("Close16.png"));

                SuperTabItem tab;
                tab = tabDesigner.CreateNewTab();
                SetProperty(tab, "Text", "Recent");
                SetProperty(tab, "KeyTips", "R");
                //SetProperty((SuperTabControlPanel)tab.AttachedControl, "BackgroundImage", RibbonControlDesigner.LoadImage("BlueBackstageBgImage.png"));
                //SetProperty((SuperTabControlPanel)tab.AttachedControl, "BackgroundImagePosition", DevComponents.DotNetBar.eStyleBackgroundImage.BottomRight);

                tab = tabDesigner.CreateNewTab();
                SetProperty(tab, "Text", "New");
                SetProperty(tab, "KeyTips", "N");
                //SetProperty((SuperTabControlPanel)tab.AttachedControl, "BackgroundImage", RibbonControlDesigner.LoadImage("BlueBackstageBgImage.png"));
                //SetProperty((SuperTabControlPanel)tab.AttachedControl, "BackgroundImagePosition", DevComponents.DotNetBar.eStyleBackgroundImage.BottomRight);

                tab = tabDesigner.CreateNewTab();
                SetProperty(tab, "Text", "Print");
                SetProperty(tab, "KeyTips", "P");
                //SetProperty((SuperTabControlPanel)tab.AttachedControl, "BackgroundImage", RibbonControlDesigner.LoadImage("BlueBackstageBgImage.png"));
                //SetProperty((SuperTabControlPanel)tab.AttachedControl, "BackgroundImagePosition", DevComponents.DotNetBar.eStyleBackgroundImage.BottomRight);

                tab = tabDesigner.CreateNewTab();
                SetProperty(tab, "Text", "Help");
                SetProperty(tab, "KeyTips", "H");
                SetProperty((SuperTabControlPanel)tab.AttachedControl, "BackgroundImage", RibbonControlDesigner.LoadImage("BlueBackstageBgImage.png"));
                SetProperty((SuperTabControlPanel)tab.AttachedControl, "BackgroundImagePosition", DevComponents.DotNetBar.eStyleBackgroundImage.BottomRight);

                // Options
                button = tabDesigner.CreateButton();
                SetProperty(button, "Text", "Options");
                SetProperty(button, "KeyTips", "T");
                SetProperty(button, "Image", RibbonControlDesigner.LoadImage("Options2.png"));

                // Exit
                button = tabDesigner.CreateButton();
                SetProperty(button, "Text", "Exit");
                SetProperty(button, "KeyTips", "X");
                SetProperty(button, "Image", RibbonControlDesigner.LoadImage("Exit2.png"));
            }
        }
        internal static void SerializeDesignerStates(IDesignerHost designerHost, BinaryWriter writer)
        {
            writer.Write(designerHost.Container.Components.Count);
            foreach (IComponent component in designerHost.Container.Components)
            {
                // write activity identifier
                writer.Write(component.Site.Name);

                //placeholder for length
                int activityDataLengthPosition = (int)writer.BaseStream.Length;

                writer.Write((int)0);

                ActivityDesigner designer = designerHost.GetDesigner(component) as ActivityDesigner;

                if (designer != null)
                {
                    int activityDataPosition = (int)writer.BaseStream.Length;

                    // write activity data
                    ((IPersistUIState)designer).SaveViewState(writer);

                    // place length
                    writer.Seek(activityDataLengthPosition, SeekOrigin.Begin);
                    writer.Write((int)writer.BaseStream.Length - activityDataPosition);
                    writer.Seek(0, SeekOrigin.End);
                }
            }
        }
Beispiel #41
0
        /// <summary>
        ///  When the verb is invoked, change the parent of the ToolStrip.
        /// </summary>
        // This is actually called...
        public void ChangeParent()
        {
            Cursor current = Cursor.Current;
            // create a transaction so this happens as an atomic unit.
            DesignerTransaction changeParent = _host.CreateTransaction("Add ToolStripContainer Transaction");

            try
            {
                Cursor.Current = Cursors.WaitCursor;
                //Add a New ToolStripContainer to the RootComponent ...
                Control root = _host.RootComponent as Control;
                if (_host.GetDesigner(root) is ParentControlDesigner rootDesigner)
                {
                    // close the DAP first - this is so that the autoshown panel on drag drop here is not conflicting with the currently opened panel
                    // if the verb was called from the panel
                    ToolStrip toolStrip = _designer.Component as ToolStrip;
                    if (toolStrip != null && _designer != null && _designer.Component != null && _provider != null)
                    {
                        DesignerActionUIService dapuisvc = _provider.GetService(typeof(DesignerActionUIService)) as DesignerActionUIService;
                        dapuisvc.HideUI(toolStrip);
                    }

                    // Get OleDragHandler ...
                    ToolboxItem        tbi = new ToolboxItem(typeof(ToolStripContainer));
                    OleDragDropHandler ddh = rootDesigner.GetOleDragHandler();
                    if (ddh != null)
                    {
                        IComponent[] newComp = ddh.CreateTool(tbi, root, 0, 0, 0, 0, false, false);
                        if (newComp[0] is ToolStripContainer tsc)
                        {
                            if (toolStrip != null)
                            {
                                IComponentChangeService changeSvc = _provider.GetService(typeof(IComponentChangeService)) as IComponentChangeService;
                                Control            newParent      = GetParent(tsc, toolStrip);
                                PropertyDescriptor controlsProp   = TypeDescriptor.GetProperties(newParent)["Controls"];
                                Control            oldParent      = toolStrip.Parent;
                                if (oldParent != null)
                                {
                                    changeSvc.OnComponentChanging(oldParent, controlsProp);
                                    //remove control from the old parent
                                    oldParent.Controls.Remove(toolStrip);
                                }

                                if (newParent != null)
                                {
                                    changeSvc.OnComponentChanging(newParent, controlsProp);
                                    //finally add & relocate the control with the new parent
                                    newParent.Controls.Add(toolStrip);
                                }

                                //fire our comp changed events
                                if (changeSvc != null && oldParent != null && newParent != null)
                                {
                                    changeSvc.OnComponentChanged(oldParent, controlsProp, null, null);
                                    changeSvc.OnComponentChanged(newParent, controlsProp, null, null);
                                }

                                //Set the Selection on the new Parent ... so that the selection is restored to the new item,
                                if (_provider.GetService(typeof(ISelectionService)) is ISelectionService selSvc)
                                {
                                    selSvc.SetSelectedComponents(new IComponent[] { tsc });
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (e is InvalidOperationException)
                {
                    IUIService uiService = (IUIService)_provider.GetService(typeof(IUIService));
                    uiService.ShowError(e.Message);
                }

                if (changeParent != null)
                {
                    changeParent.Cancel();
                    changeParent = null;
                }
            }
            finally
            {
                if (changeParent != null)
                {
                    changeParent.Commit();
                }

                Cursor.Current = current;
            }
        }
        internal static bool DeserializeDesignerStates(IDesignerHost designerHost, BinaryReader reader)
        {
            int componentCount = reader.ReadInt32();
            bool outdated = (componentCount != designerHost.Container.Components.Count);

            for (int loop = 0; loop < componentCount; loop++)
            {
                string componentName = reader.ReadString();
                int length = reader.ReadInt32();

                if (designerHost.Container.Components[componentName] != null)
                {
                    ActivityDesigner designer = designerHost.GetDesigner(designerHost.Container.Components[componentName]) as ActivityDesigner;

                    if (designer != null)
                    {
                        ((IPersistUIState)designer).LoadViewState(reader);
                    }
                    else
                    {
                        outdated = true;
                        reader.BaseStream.Position += length; // skip activity data
                    }

                }
                else
                {
                    outdated = true;
                    reader.BaseStream.Position += length; // skip activity data
                }
            }

            return outdated;
        }
 private void AddChildComponents(IComponent component, IContainer container, IDesignerHost host)
 {
     Control control = this.GetControl(component);
     if (control != null)
     {
         Control control2 = control;
         Control[] array = new Control[control2.Controls.Count];
         control2.Controls.CopyTo(array, 0);
         IContainer container2 = null;
         for (int i = 0; i < array.Length; i++)
         {
             ISite site = array[i].Site;
             if (site != null)
             {
                 string name = site.Name;
                 if (container.Components[name] != null)
                 {
                     name = null;
                 }
                 container2 = site.Container;
                 if (container2 != null)
                 {
                     container2.Remove(array[i]);
                 }
                 if (name != null)
                 {
                     container.Add(array[i], name);
                 }
                 else
                 {
                     container.Add(array[i]);
                 }
                 if (array[i].Parent != control2)
                 {
                     control2.Controls.Add(array[i]);
                 }
                 else
                 {
                     int childIndex = control2.Controls.GetChildIndex(array[i]);
                     control2.Controls.Remove(array[i]);
                     control2.Controls.Add(array[i]);
                     control2.Controls.SetChildIndex(array[i], childIndex);
                 }
                 IComponentInitializer designer = host.GetDesigner(component) as IComponentInitializer;
                 if (designer != null)
                 {
                     designer.InitializeExistingComponent(null);
                 }
                 this.AddChildComponents(array[i], container, host);
             }
         }
     }
 }
        public override Object EditValue(ITypeDescriptorContext context, IServiceProvider provider, Object value)
        {
            Debug.Assert(context.Instance is Control, "Expected control");
            Control ctrl = (Control)context.Instance;

            IServiceProvider serviceProvider;
            ISite            site = ctrl.Site;

            if (site == null && ctrl.Page != null)
            {
                site = ctrl.Page.Site;
            }
            if (site != null)
            {
                serviceProvider = site;
            }
            else
            {
                serviceProvider = provider;
            }
            Debug.Assert(serviceProvider != null,
                         "Failed to get the serviceProvider");

            IComponentChangeService changeService =
                (IComponentChangeService)serviceProvider.GetService(typeof(IComponentChangeService));

            IDesignerHost designerHost =
                (IDesignerHost)serviceProvider.GetService(typeof(IDesignerHost));

            Debug.Assert(designerHost != null,
                         "Must always have access to IDesignerHost service");

            IDeviceSpecificDesigner dsDesigner =
                designerHost.GetDesigner(ctrl) as IDeviceSpecificDesigner;

            Debug.Assert(dsDesigner != null,
                         "Expected component designer to implement IDeviceSpecificDesigner");

            IMobileWebFormServices wfServices =
                (IMobileWebFormServices)serviceProvider.GetService(typeof(IMobileWebFormServices));

            DialogResult result = DialogResult.Cancel;

            DesignerTransaction transaction = designerHost.CreateTransaction(_appliedDeviceFiltersDescription);

            try
            {
                if (changeService != null)
                {
                    try
                    {
                        changeService.OnComponentChanging(ctrl, null);
                    }
                    catch (CheckoutException ce)
                    {
                        if (ce == CheckoutException.Canceled)
                        {
                            return(value);
                        }
                        throw;
                    }
                }

                try
                {
                    AppliedDeviceFiltersDialog dialog =
                        new AppliedDeviceFiltersDialog(dsDesigner, MobileControlDesigner.MergingContextChoices);
                    IWindowsFormsEditorService edSvc =
                        (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                    result = edSvc.ShowDialog(dialog);
                }
                finally
                {
                    if (changeService != null && result != DialogResult.Cancel)
                    {
                        changeService.OnComponentChanged(ctrl, null, null, null);
                    }
                }
            }
            finally
            {
                if (transaction != null)
                {
                    if (result == DialogResult.OK)
                    {
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Cancel();
                    }
                }
            }

            return(value);
        }
Beispiel #45
0
        protected override IComponent[] CreateComponentsCore(IDesignerHost host)
        {
            IComponent[] components = base.CreateComponentsCore(host);

            Control parentControl = null;
            ControlDesigner parentControlDesigner = null;
            TabStrip tabStrip = null;
            IComponentChangeService changeSvc = (IComponentChangeService)host.GetService(typeof(IComponentChangeService));

            // fish out the parent we're adding the TabStrip to.
            if (components.Length > 0 && components[0] is TabStrip) {
                tabStrip = components[0] as TabStrip;

                ITreeDesigner tabStripDesigner = host.GetDesigner(tabStrip) as ITreeDesigner;
                parentControlDesigner = tabStripDesigner.Parent as ControlDesigner;
                if (parentControlDesigner != null) {
                    parentControl = parentControlDesigner.Control;
                }
            }

            // Create a ControlSwitcher on the same parent.

            if (host != null) {
                TabPageSwitcher controlSwitcher = null;

                DesignerTransaction t = null;
                try {
                    try {
                        t = host.CreateTransaction("add tabswitcher");
                    }
                    catch (CheckoutException ex) {
                        if (ex == CheckoutException.Canceled) {
                            return components;
                        }
                        throw ex;
                    }
                    MemberDescriptor controlsMember = TypeDescriptor.GetProperties(parentControlDesigner)["Controls"];
                    controlSwitcher = host.CreateComponent(typeof(TabPageSwitcher)) as TabPageSwitcher;

                    if (changeSvc != null) {
                        changeSvc.OnComponentChanging(parentControl, controlsMember);
                        changeSvc.OnComponentChanged(parentControl, controlsMember, null, null);
                    }

                    Dictionary<string, object> propertyValues = new Dictionary<string, object>();
                    propertyValues["Location"] = new Point(tabStrip.Left, tabStrip.Bottom + 3);
                    propertyValues["TabStrip"] = tabStrip;

                    SetProperties(controlSwitcher, propertyValues, host);

                }
                finally {
                    if (t != null)
                        t.Commit();
                }

                if (controlSwitcher != null) {
                    IComponent[] newComponents = new IComponent[components.Length + 1];
                    Array.Copy(components, newComponents, components.Length);
                    newComponents[newComponents.Length - 1] = controlSwitcher;
                    return newComponents;
                }

            }

            return components;
        }
Beispiel #46
0
        /// <summary>
        ///  When any MouseMove message enters the BehaviorService's AdornerWindow (mousemove, ncmousemove) it is first passed here, to the top-most Behavior in the BehaviorStack.  Returning 'true' from this function signifies that  the Message was 'handled' by the Behavior and should not continue to be processed.
        /// </summary>
        public override bool OnMouseMove(Glyph g, MouseButtons button, Point mouseLoc)
        {
            bool retVal = false;
            ToolStripItemGlyph glyph     = g as ToolStripItemGlyph;
            ToolStripItem      glyphItem = glyph.Item;
            ISelectionService  selSvc    = GetSelectionService(glyphItem);

            if (selSvc is null || glyphItem.Site is null || MouseHandlerPresent(glyphItem))
            {
                return(false);
            }
            if (!selSvc.GetComponentSelected(glyphItem))
            {
                PaintInsertionMark(glyphItem);
                retVal = false;
            }

            if (button == MouseButtons.Left && glyph != null && glyph.ItemDesigner != null && !glyph.ItemDesigner.IsEditorActive)
            {
                Rectangle     dragBox      = Rectangle.Empty;
                IDesignerHost designerHost = (IDesignerHost)glyphItem.Site.GetService(typeof(IDesignerHost));
                Debug.Assert(designerHost != null, "Invalid DesignerHost");
                if (glyphItem.Placement == ToolStripItemPlacement.Overflow || (glyphItem.Placement == ToolStripItemPlacement.Main && !(glyphItem.IsOnDropDown)))
                {
                    ToolStripItemDesigner itemDesigner    = glyph.ItemDesigner;
                    ToolStrip             parentToolStrip = itemDesigner.GetMainToolStrip();
                    if (designerHost.GetDesigner(parentToolStrip) is ToolStripDesigner parentDesigner)
                    {
                        dragBox = parentDesigner.DragBoxFromMouseDown;
                    }
                }
                else if (glyphItem.IsOnDropDown)
                {
                    //Get the OwnerItem's Designer and set the value...
                    if (glyphItem.Owner is ToolStripDropDown parentDropDown)
                    {
                        ToolStripItem ownerItem = parentDropDown.OwnerItem;
                        if (designerHost.GetDesigner(ownerItem) is ToolStripItemDesigner ownerItemDesigner)
                        {
                            dragBox = ownerItemDesigner.dragBoxFromMouseDown;
                        }
                    }
                }
                // If the mouse moves outside the rectangle, start the drag.
                if (dragBox != Rectangle.Empty && !dragBox.Contains(mouseLoc.X, mouseLoc.Y))
                {
                    if (_timer != null)
                    {
                        _timer.Enabled = false;
                        _timer.Tick   -= new System.EventHandler(OnDoubleClickTimerTick);
                        _timer.Dispose();
                        _timer = null;
                    }

                    // Proceed with the drag and drop, passing in the list item.
                    try
                    {
                        ArrayList   dragItems = new ArrayList();
                        ICollection selComps  = selSvc.GetSelectedComponents();
                        //create our list of controls-to-drag
                        foreach (IComponent comp in selComps)
                        {
                            if (comp is ToolStripItem item)
                            {
                                dragItems.Add(item);
                            }
                        }

                        //Start Drag-Drop only if ToolStripItem is the primary Selection
                        if (selSvc.PrimarySelection is ToolStripItem selectedItem)
                        {
                            ToolStrip owner = selectedItem.Owner;
                            ToolStripItemDataObject data = new ToolStripItemDataObject(dragItems, selectedItem, owner);
                            DropSource.QueryContinueDrag += new QueryContinueDragEventHandler(QueryContinueDrag);
                            if (glyphItem is ToolStripDropDownItem ddItem)
                            {
                                if (designerHost.GetDesigner(ddItem) is ToolStripMenuItemDesigner itemDesigner)
                                {
                                    itemDesigner.InitializeBodyGlyphsForItems(false, ddItem);
                                    ddItem.HideDropDown();
                                }
                            }
                            else if (glyphItem.IsOnDropDown && !glyphItem.IsOnOverflow)
                            {
                                ToolStripDropDown     dropDown  = glyphItem.GetCurrentParent() as ToolStripDropDown;
                                ToolStripDropDownItem ownerItem = dropDown.OwnerItem as ToolStripDropDownItem;
                                selSvc.SetSelectedComponents(new IComponent[] { ownerItem }, SelectionTypes.Replace);
                            }
                            DropSource.DoDragDrop(data, DragDropEffects.All);
                        }
                    }
                    finally
                    {
                        DropSource.QueryContinueDrag -= new QueryContinueDragEventHandler(QueryContinueDrag);
                        //Reset all Drag-Variables
                        SetParentDesignerValuesForDragDrop(glyphItem, false, Point.Empty);
                        ToolStripDesigner.s_dragItem = null;
                        _dropSource = null;
                    }
                    retVal = false;
                }
            }
            return(retVal);
        }
 private void GetAssociatedComponents(IComponent component, IDesignerHost host, ArrayList list)
 {
     ComponentDesigner designer = host.GetDesigner(component) as ComponentDesigner;
     if (designer != null)
     {
         foreach (IComponent component2 in designer.AssociatedComponents)
         {
             list.Add(component2);
             this.GetAssociatedComponents(component2, host, list);
         }
     }
 }
Beispiel #48
0
        //  OLE DragDrop virtual methods
        /// <summary>
        ///  OnDragDrop can be overridden so that a Behavior can specify its own Drag/Drop rules.
        /// </summary>
        public override void OnDragDrop(Glyph g, DragEventArgs e)
        {
            ToolStripItem currentDropItem = ToolStripDesigner.s_dragItem;

            // Ensure that the list item index is contained in the data.
            if (e.Data is ToolStripItemDataObject && currentDropItem != null)
            {
                ToolStripItemDataObject data = (ToolStripItemDataObject)e.Data;
                // Get the PrimarySelection before the Drag operation...
                ToolStripItem selectedItem = data.PrimarySelection;
                IDesignerHost designerHost = (IDesignerHost)currentDropItem.Site.GetService(typeof(IDesignerHost));
                Debug.Assert(designerHost != null, "Invalid DesignerHost");
                //Do DragDrop only if currentDropItem has changed.
                if (currentDropItem != selectedItem && designerHost != null)
                {
                    ArrayList components      = data.DragComponents;
                    ToolStrip parentToolStrip = currentDropItem.GetCurrentParent() as ToolStrip;
                    int       primaryIndex    = -1;
                    string    transDesc;
                    bool      copy = (e.Effect == DragDropEffects.Copy);
                    if (components.Count == 1)
                    {
                        string name = TypeDescriptor.GetComponentName(components[0]);
                        if (name is null || name.Length == 0)
                        {
                            name = components[0].GetType().Name;
                        }
                        transDesc = string.Format(copy ? SR.BehaviorServiceCopyControl : SR.BehaviorServiceMoveControl, name);
                    }
                    else
                    {
                        transDesc = string.Format(copy ? SR.BehaviorServiceCopyControls : SR.BehaviorServiceMoveControls, components.Count);
                    }

                    DesignerTransaction designerTransaction = designerHost.CreateTransaction(transDesc);
                    try
                    {
                        IComponentChangeService changeSvc = (IComponentChangeService)currentDropItem.Site.GetService(typeof(IComponentChangeService));
                        if (changeSvc != null)
                        {
                            if (parentToolStrip is ToolStripDropDown dropDown)
                            {
                                ToolStripItem ownerItem = dropDown.OwnerItem;
                                changeSvc.OnComponentChanging(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"]);
                            }
                            else
                            {
                                changeSvc.OnComponentChanging(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"]);
                            }
                        }

                        // If we are copying, then we want to make a copy of the components we are dragging
                        if (copy)
                        {
                            // Remember the primary selection if we had one
                            if (selectedItem != null)
                            {
                                primaryIndex = components.IndexOf(selectedItem);
                            }
                            ToolStripKeyboardHandlingService keyboardHandlingService = GetKeyBoardHandlingService(selectedItem);
                            if (keyboardHandlingService != null)
                            {
                                keyboardHandlingService.CopyInProgress = true;
                            }
                            components = DesignerUtils.CopyDragObjects(components, currentDropItem.Site) as ArrayList;
                            if (keyboardHandlingService != null)
                            {
                                keyboardHandlingService.CopyInProgress = false;
                            }
                            if (primaryIndex != -1)
                            {
                                selectedItem = components[primaryIndex] as ToolStripItem;
                            }
                        }

                        if (e.Effect == DragDropEffects.Move || copy)
                        {
                            ISelectionService selSvc = GetSelectionService(currentDropItem);
                            if (selSvc != null)
                            {
                                // Insert the item.
                                if (parentToolStrip is ToolStripOverflow)
                                {
                                    parentToolStrip = (((ToolStripOverflow)parentToolStrip).OwnerItem).Owner;
                                }

                                int indexOfItemUnderMouseToDrop = parentToolStrip.Items.IndexOf(ToolStripDesigner.s_dragItem);
                                if (indexOfItemUnderMouseToDrop != -1)
                                {
                                    int indexOfPrimarySelection = 0;
                                    if (selectedItem != null)
                                    {
                                        indexOfPrimarySelection = parentToolStrip.Items.IndexOf(selectedItem);
                                    }

                                    if (indexOfPrimarySelection != -1 && indexOfItemUnderMouseToDrop > indexOfPrimarySelection)
                                    {
                                        indexOfItemUnderMouseToDrop--;
                                    }
                                    foreach (ToolStripItem item in components)
                                    {
                                        parentToolStrip.Items.Insert(indexOfItemUnderMouseToDrop, item);
                                    }
                                }
                                selSvc.SetSelectedComponents(new IComponent[] { selectedItem }, SelectionTypes.Primary | SelectionTypes.Replace);
                            }
                        }
                        if (changeSvc != null)
                        {
                            ToolStripDropDown dropDown = parentToolStrip as ToolStripDropDown;
                            if (dropDown != null)
                            {
                                ToolStripItem ownerItem = dropDown.OwnerItem;
                                changeSvc.OnComponentChanged(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"], null, null);
                            }
                            else
                            {
                                changeSvc.OnComponentChanged(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"], null, null);
                            }

                            //fire extra changing/changed events.
                            if (copy)
                            {
                                if (dropDown != null)
                                {
                                    ToolStripItem ownerItem = dropDown.OwnerItem;
                                    changeSvc.OnComponentChanging(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"]);
                                    changeSvc.OnComponentChanged(ownerItem, TypeDescriptor.GetProperties(ownerItem)["DropDownItems"], null, null);
                                }
                                else
                                {
                                    changeSvc.OnComponentChanging(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"]);
                                    changeSvc.OnComponentChanged(parentToolStrip, TypeDescriptor.GetProperties(parentToolStrip)["Items"], null, null);
                                }
                            }
                        }

                        //If Parent is DropDown... we have to manage the Glyphs ....
                        foreach (ToolStripItem item in components)
                        {
                            if (item is ToolStripDropDownItem)
                            {
                                if (designerHost.GetDesigner(item) is ToolStripMenuItemDesigner itemDesigner)
                                {
                                    itemDesigner.InitializeDropDown();
                                }
                            }
                            if (item.GetCurrentParent() is ToolStripDropDown dropDown && !(dropDown is ToolStripOverflow))
                            {
                                if (dropDown.OwnerItem is ToolStripDropDownItem ownerItem)
                                {
                                    if (designerHost.GetDesigner(ownerItem) is ToolStripMenuItemDesigner ownerDesigner)
                                    {
                                        ownerDesigner.InitializeBodyGlyphsForItems(false, ownerItem);
                                        ownerDesigner.InitializeBodyGlyphsForItems(true, ownerItem);
                                    }
                                }
                            }
                        }
                        // Refresh on SelectionManager...
                        BehaviorService bSvc = GetBehaviorService(currentDropItem);
                        if (bSvc != null)
                        {
                            bSvc.SyncSelection();
                        }
                    }
                    catch (Exception ex)
                    {
                        if (designerTransaction != null)
                        {
                            designerTransaction.Cancel();
                            designerTransaction = null;
                        }
                        if (ClientUtils.IsCriticalException(ex))
                        {
                            throw;
                        }
                    }
                    finally
                    {
                        if (designerTransaction != null)
                        {
                            designerTransaction.Commit();
                            designerTransaction = null;
                        }
                    }
                }
            }
        }
Beispiel #49
0
        /// <summary>
        /// Create new instance of specified type within the designer host, if provided.
        /// </summary>
        /// <param name="itemType">Type of the item to create.</param>
        /// <param name="host">Designer host used if provided.</param>
        /// <returns>Reference to new instance.</returns>
        public static object CreateInstance(Type itemType, IDesignerHost host)
        {
            object retObj = null;

            // Cannot use the designer host to create component unless the type implements IComponent
            if (typeof(IComponent).IsAssignableFrom(itemType) && (host != null))
            {
                // Ask host to create component for us
                retObj = host.CreateComponent(itemType, null);

                // If the new object has an associated designer then use that now to initialize the instance
                IComponentInitializer designer = host.GetDesigner((IComponent)retObj) as IComponentInitializer;
                if (designer != null)
                    designer.InitializeNewComponent(null);
            }
            else
            {
                // Cannot use host for creation, so do it the standard way instead
                retObj = TypeDescriptor.CreateInstance(host, itemType, null, null);
            }

            return retObj;
        }
        /// <summary>
        ///  Here is where all the fun stuff starts.  We create the structure and apply the naming here.
        /// </summary>
        private void CreateStandardMenuStrip(System.ComponentModel.Design.IDesignerHost host, MenuStrip tool)
        {
            // build the static menu items structure.
            string[][] menuItemNames = new string[][] {
                new string[] { SR.StandardMenuFile, SR.StandardMenuNew, SR.StandardMenuOpen, "-", SR.StandardMenuSave, SR.StandardMenuSaveAs, "-", SR.StandardMenuPrint, SR.StandardMenuPrintPreview, "-", SR.StandardMenuExit },
                new string[] { SR.StandardMenuEdit, SR.StandardMenuUndo, SR.StandardMenuRedo, "-", SR.StandardMenuCut, SR.StandardMenuCopy, SR.StandardMenuPaste, "-", SR.StandardMenuSelectAll },
                new string[] { SR.StandardMenuTools, SR.StandardMenuCustomize, SR.StandardMenuOptions },
                new string[] { SR.StandardMenuHelp, SR.StandardMenuContents, SR.StandardMenuIndex, SR.StandardMenuSearch, "-", SR.StandardMenuAbout }
            };

            // build the static menu items image list that maps one-one with above menuItems structure. this is required so that the in LOCALIZED build we dont use the Localized item string.
            string[][] menuItemImageNames = new string[][] {
                new string[] { "", "new", "open", "-", "save", "", "-", "print", "printPreview", "-", "" },
                new string[] { "", "", "", "-", "cut", "copy", "paste", "-", "" },
                new string[] { "", "", "" },
                new string[] { "", "", "", "", "-", "" }
            };

            Keys[][] menuItemShortcuts = new Keys[][] {
                new Keys[] { /*File*/ Keys.None, /*New*/ Keys.Control | Keys.N, /*Open*/ Keys.Control | Keys.O, /*Separator*/ Keys.None, /*Save*/ Keys.Control | Keys.S, /*SaveAs*/ Keys.None, Keys.None, /*Print*/ Keys.Control | Keys.P, /*PrintPreview*/ Keys.None, /*Separator*/ Keys.None, /*Exit*/ Keys.None },
                new Keys[] { /*Edit*/ Keys.None, /*Undo*/ Keys.Control | Keys.Z, /*Redo*/ Keys.Control | Keys.Y, /*Separator*/ Keys.None, /*Cut*/ Keys.Control | Keys.X, /*Copy*/ Keys.Control | Keys.C, /*Paste*/ Keys.Control | Keys.V, /*Separator*/ Keys.None, /*SelectAll*/ Keys.None },
                new Keys[] { /*Tools*/ Keys.None, /*Customize*/ Keys.None, /*Options*/ Keys.None },
                new Keys[] { /*Help*/ Keys.None, /*Contents*/ Keys.None, /*Index*/ Keys.None, /*Search*/ Keys.None, /*Separator*/ Keys.None, /*About*/ Keys.None }
            };

            Debug.Assert(host != null, "can't create standard menu without designer _host.");
            if (host == null)
            {
                return;
            }
            tool.SuspendLayout();
            ToolStripDesigner.s_autoAddNewItems = false;
            // create a transaction so this happens as an atomic unit.
            DesignerTransaction createMenu = _host.CreateTransaction(SR.StandardMenuCreateDesc);

            try
            {
                INameCreationService nameCreationService = (INameCreationService)_provider.GetService(typeof(INameCreationService));
                string defaultName = "standardMainMenuStrip";
                string name        = defaultName;
                int    index       = 1;

                if (host != null)
                {
                    while (_host.Container.Components[name] != null)
                    {
                        name = defaultName + (index++).ToString(CultureInfo.InvariantCulture);
                    }
                }

                // now build the menu items themselves.
                for (int j = 0; j < menuItemNames.Length; j++)
                {
                    string[]          menuArray = menuItemNames[j];
                    ToolStripMenuItem rootItem  = null;
                    for (int i = 0; i < menuArray.Length; i++)
                    {
                        name = null;
                        // for separators, just use the default name.  Otherwise, remove any non-characters and  get the name from the text.
                        string itemText = menuArray[i];
                        name = NameFromText(itemText, typeof(ToolStripMenuItem), nameCreationService, true);
                        ToolStripItem item = null;
                        if (name.Contains("Separator"))
                        {
                            // create the componennt.
                            item = (ToolStripSeparator)_host.CreateComponent(typeof(ToolStripSeparator), name);
                            IDesigner designer = _host.GetDesigner(item);
                            if (designer is ComponentDesigner)
                            {
                                ((ComponentDesigner)designer).InitializeNewComponent(null);
                            }
                            item.Text = itemText;
                        }
                        else
                        {
                            // create the componennt.
                            item = (ToolStripMenuItem)_host.CreateComponent(typeof(ToolStripMenuItem), name);
                            IDesigner designer = _host.GetDesigner(item);
                            if (designer is ComponentDesigner)
                            {
                                ((ComponentDesigner)designer).InitializeNewComponent(null);
                            }
                            item.Text = itemText;
                            Keys shortcut = menuItemShortcuts[j][i];
                            if ((item is ToolStripMenuItem) && shortcut != Keys.None)
                            {
                                if (!ToolStripManager.IsShortcutDefined(shortcut) && ToolStripManager.IsValidShortcut(shortcut))
                                {
                                    ((ToolStripMenuItem)item).ShortcutKeys = shortcut;
                                }
                            }
                            Bitmap image = null;
                            try
                            {
                                image = GetImage(menuItemImageNames[j][i]);
                            }
                            catch
                            {
                                // eat the exception.. as you may not find image for all MenuItems.
                            }
                            if (image != null)
                            {
                                PropertyDescriptor imageProperty = TypeDescriptor.GetProperties(item)["Image"];
                                Debug.Assert(imageProperty != null, "Could not find 'Image' property in ToolStripItem.");
                                if (imageProperty != null)
                                {
                                    imageProperty.SetValue(item, image);
                                }
                                item.ImageTransparentColor = Color.Magenta;
                            }
                        }

                        // the first item in each array is the root item.
                        if (i == 0)
                        {
                            rootItem = (ToolStripMenuItem)item;
                            rootItem.DropDown.SuspendLayout();
                        }
                        else
                        {
                            rootItem.DropDownItems.Add(item);
                        }
                        //If Last SubItem Added the Raise the Events
                        if (i == menuArray.Length - 1)
                        {
                            // member is OK to be null...
                            MemberDescriptor member = TypeDescriptor.GetProperties(rootItem)["DropDownItems"];
                            _componentChangeSvc.OnComponentChanging(rootItem, member);
                            _componentChangeSvc.OnComponentChanged(rootItem, member, null, null);
                        }
                    }

                    // finally, add it to the MainMenu.
                    rootItem.DropDown.ResumeLayout(false);
                    tool.Items.Add(rootItem);
                    //If Last SubItem Added the Raise the Events
                    if (j == menuItemNames.Length - 1)
                    {
                        // member is OK to be null...
                        MemberDescriptor topMember = TypeDescriptor.GetProperties(tool)["Items"];
                        _componentChangeSvc.OnComponentChanging(tool, topMember);
                        _componentChangeSvc.OnComponentChanged(tool, topMember, null, null);
                    }
                }
            }
            catch (Exception e)
            {
                if (e is InvalidOperationException)
                {
                    IUIService uiService = (IUIService)_provider.GetService(typeof(IUIService));
                    uiService.ShowError(e.Message);
                }
                if (createMenu != null)
                {
                    createMenu.Cancel();
                    createMenu = null;
                }
            }
            finally
            {
                ToolStripDesigner.s_autoAddNewItems = true;
                if (createMenu != null)
                {
                    createMenu.Commit();
                    createMenu = null;
                }
                tool.ResumeLayout();
                // Select the Main Menu...
                ISelectionService selSvc = (ISelectionService)_provider.GetService(typeof(ISelectionService));
                if (selSvc != null)
                {
                    selSvc.SetSelectedComponents(new object[] { _designer.Component });
                }
                //Refresh the Glyph
                DesignerActionUIService actionUIService = (DesignerActionUIService)_provider.GetService(typeof(DesignerActionUIService));
                if (actionUIService != null)
                {
                    actionUIService.Refresh(_designer.Component);
                }
                // this will invalidate the Selection Glyphs.
                SelectionManager selMgr = (SelectionManager)_provider.GetService(typeof(SelectionManager));
                selMgr.Refresh();
            }
        }
 internal static void SerializeDesignerStates(IDesignerHost designerHost, BinaryWriter writer)
 {
     writer.Write(designerHost.Container.Components.Count);
     foreach (IComponent component in designerHost.Container.Components)
     {
         writer.Write(component.Site.Name);
         int length = (int) writer.BaseStream.Length;
         writer.Write(0);
         ActivityDesigner designer = designerHost.GetDesigner(component) as ActivityDesigner;
         if (designer != null)
         {
             int num2 = (int) writer.BaseStream.Length;
             ((IPersistUIState) designer).SaveViewState(writer);
             writer.Seek(length, SeekOrigin.Begin);
             writer.Write((int) (((int) writer.BaseStream.Length) - num2));
             writer.Seek(0, SeekOrigin.End);
         }
     }
 }
 protected virtual IComponent[] CreateComponentsCore(IDesignerHost host, IDictionary defaultValues)
 {
     IComponent[] componentArray = this.CreateComponentsCore(host);
     if (host != null)
     {
         for (int i = 0; i < componentArray.Length; i++)
         {
             IComponentInitializer designer = host.GetDesigner(componentArray[i]) as IComponentInitializer;
             if (designer != null)
             {
                 bool flag = true;
                 try
                 {
                     designer.InitializeNewComponent(defaultValues);
                     flag = false;
                 }
                 finally
                 {
                     if (flag)
                     {
                         for (int j = 0; j < componentArray.Length; j++)
                         {
                             host.DestroyComponent(componentArray[j]);
                         }
                     }
                 }
             }
         }
     }
     return componentArray;
 }