IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VB.NET Discussion :

ComponentModel .Design. IMenuCommandService


Sujet :

VB.NET

  1. #1
    Futur Membre du Club Avatar de Btacorn
    Homme Profil pro
    Officier de la marine marchande
    Inscrit en
    Avril 2020
    Messages
    24
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Officier de la marine marchande

    Informations forums :
    Inscription : Avril 2020
    Messages : 24
    Points : 7
    Points
    7
    Par défaut ComponentModel .Design. IMenuCommandService
    Bonjour,
    J'utilise entre autre System.ComponentModel.Design.StandardCommands de ComponentModel.Design.IMenuCommandService
    Uniquement System.ComponentModel.Design.StandardCommands.delete fonctionne mais pas les autres commandes.
    Il s'agit d'un concepteur de fenêtre avec un loader de type BasicHostLoader (qui sérialize du Xml) tiré tout droit d'ici https://docs.microsoft.com/en-us/arc...-framework-2-0
    Code VB de la classe BasicHostLoader.vb
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    Imports System
    Imports System.ComponentModel
    Imports System.ComponentModel.Design
    Imports System.ComponentModel.Design.Serialization
    Imports System.Collections
    Imports System.Diagnostics
    Imports System.Globalization
    Imports System.IO
    Imports System.Reflection
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports System.Windows.Forms
    Imports System.Xml
    Imports System.Runtime.InteropServices
     
    Namespace Loader
     
        ''' <summary>
        ''' Inherits from BasicDesignerLoader. It can persist the HostSurface
        ''' to an Xml file and can also parse the Xml file to re-create the
        ''' RootComponent and all the components that it hosts.
        ''' </summary>
        Friend Class BasicHostLoader
            Inherits BasicDesignerLoader
     
            Private root As IComponent
     
            Private dirty As Boolean = True
            Private unsaved As Boolean
            Private fileName As String
            Private host As IDesignerLoaderHost
            Private xmlDocument As XmlDocument
            Private Shared ReadOnly propertyAttributes As Object = New Attribute() {DesignOnlyAttribute.No}
            Private rootComponentType As Type
     
     
    #Region "Constructors"
     
            ''' Empty constructor simply creates a new form.
            Public Sub New(ByVal rootComponentType As Type)
                Me.rootComponentType = rootComponentType
     
                Modified = True
            End Sub
     
     
            ''' <summary>
            ''' This constructor takes a file name.  This file
            ''' should exist on disk and consist of XML that
            ''' can be read by a data set.
            ''' </summary>
            Public Sub New(ByVal fileName As String)
                If Equals(fileName, Nothing) Then
                    Throw New ArgumentNullException("fileName")
                End If
     
                Me.fileName = fileName
            End Sub
     
    #End Region
     
    #Region "Overriden methods of BasicDesignerLoader"
     
            ' Called by the host when we load a document.
            Protected Overrides Sub PerformLoad(ByVal designerSerializationManager As IDesignerSerializationManager)
                host = LoaderHost
     
                If host Is Nothing Then
                    Throw New ArgumentNullException("BasicHostLoader.BeginLoad: Invalid designerLoaderHost.")
                End If
     
     
                ' The loader will put error messages in here.
                Dim errors As ArrayList = New ArrayList()
                Dim successful = True
                Dim baseClassName As String
     
     
                ' If no filename was passed in, just create a form and be done with it.  If a file name
                ' was passed, read it.
                If Equals(fileName, Nothing) Then
     
                    If rootComponentType Is GetType(Form) Then
                        host.CreateComponent(GetType(Form))
                        baseClassName = "Form1"
     
                    ElseIf rootComponentType Is GetType(UserControl) Then
                        host.CreateComponent(GetType(UserControl))
                        baseClassName = "UserControl1"
                    ElseIf rootComponentType Is GetType(Component) Then
                        host.CreateComponent(GetType(Component))
                        baseClassName = "Component1"
                    Else
                        Throw New Exception("Undefined Host Type: " & rootComponentType.ToString())
                    End If
                Else
                    baseClassName = ReadFile(fileName, errors, xmlDocument)
                End If
     
     
                ' Now that we are done with the load work, we need to begin to listen to events.
                ' Listening to event notifications is how a designer "Loader" can also be used
                ' to save data.  If we wanted to integrate this loader with source code control,
                ' we would listen to the "ing" events as well as the "ed" events.
                Dim cs As IComponentChangeService = TryCast(host.GetService(GetType(IComponentChangeService)), IComponentChangeService)
     
                If cs IsNot Nothing Then
                    AddHandler cs.ComponentChanged, New ComponentChangedEventHandler(AddressOf OnComponentChanged)
                    AddHandler cs.ComponentAdded, New ComponentEventHandler(AddressOf OnComponentAddedRemoved)
                    AddHandler cs.ComponentRemoved, New ComponentEventHandler(AddressOf OnComponentAddedRemoved)
                End If
     
     
                ' Let the host know we are done loading.
                host.EndLoad(baseClassName, successful, errors)
     
                ' We've just loaded a document, so you can bet we need to flush changes.
                dirty = True
                unsaved = False
            End Sub
     
     
            ''' <summary>
            ''' This method is called by the designer host whenever it wants the
            ''' designer loader to flush any pending changes.  Flushing changes
            ''' does not mean the same thing as saving to disk.  For example,
            ''' In Visual Studio, flushing changes causes new code to be generated
            ''' and inserted into the text editing window.  The user can edit
            ''' the new code in the editing window, but nothing has been saved
            ''' to disk.  This sample adheres to this separation between flushing
            ''' and saving, since a flush occurs whenever the code windows are
            ''' displayed or there is a build. Neither of those items demands a save.
            ''' </summary>
            Protected Overrides Sub PerformFlush(ByVal designerSerializationManager As IDesignerSerializationManager)
                ' Nothing to flush if nothing has changed.
                If Not dirty Then
                    Return
                End If
     
                PerformFlushWorker()
            End Sub
     
            Public Overrides Sub Dispose()
                ' Always remove attached event handlers in Dispose.
                Dim cs As IComponentChangeService = TryCast(host.GetService(GetType(IComponentChangeService)), IComponentChangeService)
     
                If cs IsNot Nothing Then
                    RemoveHandler cs.ComponentChanged, New ComponentChangedEventHandler(AddressOf OnComponentChanged)
                    RemoveHandler cs.ComponentAdded, New ComponentEventHandler(AddressOf OnComponentAddedRemoved)
                    RemoveHandler cs.ComponentRemoved, New ComponentEventHandler(AddressOf OnComponentAddedRemoved)
                End If
            End Sub
     
     
    #End Region
     
    #Region "Helper methods"
     
            ''' <summary>
            ''' Simple helper method that returns true if the given type converter supports
            ''' two-way conversion of the given type.
            ''' </summary>
            Private Function GetConversionSupported(ByVal converter As TypeConverter, ByVal conversionType As Type) As Boolean
                Return converter.CanConvertFrom(conversionType) AndAlso converter.CanConvertTo(conversionType)
            End Function
     
     
            ''' <summary>
            ''' As soon as things change, we're dirty, so Flush()ing will give us a new
            ''' xmlDocument and codeCompileUnit.
            ''' </summary>
            Private Sub OnComponentChanged(ByVal sender As Object, ByVal ce As ComponentChangedEventArgs)
                dirty = True
                unsaved = True
     
            End Sub
     
            Private Sub OnComponentAddedRemoved(ByVal sender As Object, ByVal ce As ComponentEventArgs)
                dirty = True
                unsaved = True
     
            End Sub
     
     
            ''' <summary>
            ''' This method prompts the user to see if it is OK to dispose this document.  
            ''' The prompt only happens if the user has made changes.
            ''' </summary>
            Friend Function PromptDispose() As Boolean
                If dirty OrElse unsaved Then
     
                    Select Case MessageBox.Show("Save changes to existing designer?", "Unsaved Changes", MessageBoxButtons.YesNoCancel)
                        Case DialogResult.Yes
                            Save(False)
                        Case DialogResult.Cancel
                            Return False
                    End Select
                End If
     
                Return True
            End Function
     
     
    #End Region
     
    #Region "Serialize - Flush"
            ''' <summary>
            ''' This will recussively go through all the objects in the tree and
            ''' serialize them to Xml
            ''' </summary>
            Public Sub PerformFlushWorker()
                Dim document As XmlDocument = New XmlDocument()
                document.AppendChild(document.CreateElement("DOCUMENT_ELEMENT"))
                Dim idh = CType(host.GetService(GetType(IDesignerHost)), IDesignerHost)
                root = idh.RootComponent
                Dim nametable As Hashtable = New Hashtable(idh.Container.Components.Count)
                Dim manager As IDesignerSerializationManager = TryCast(host.GetService(GetType(IDesignerSerializationManager)), IDesignerSerializationManager)
                document.DocumentElement.AppendChild(WriteObject(document, nametable, root))
     
                For Each comp As IComponent In idh.Container.Components
     
                    If comp IsNot root AndAlso Not nametable.ContainsKey(comp) Then
                        document.DocumentElement.AppendChild(WriteObject(document, nametable, comp))
                    End If
                Next
     
                xmlDocument = document
            End Sub
     
            Private Function WriteObject(ByVal document As XmlDocument, ByVal nametable As IDictionary, ByVal value As Object) As XmlNode
                Dim idh = CType(host.GetService(GetType(IDesignerHost)), IDesignerHost)
                Debug.Assert(value IsNot Nothing, "Should not invoke WriteObject with a null value")
                Dim node As XmlNode = document.CreateElement("Object")
                Dim typeAttr = document.CreateAttribute("type")
                typeAttr.Value = value.GetType().AssemblyQualifiedName
                node.Attributes.Append(typeAttr)
                Dim component As IComponent = TryCast(value, IComponent)
     
                If component IsNot Nothing AndAlso component.Site IsNot Nothing AndAlso Not Equals(component.Site.Name, Nothing) Then
                    Dim nameAttr = document.CreateAttribute("name")
                    nameAttr.Value = component.Site.Name
                    node.Attributes.Append(nameAttr)
                    Debug.Assert(nametable(component) Is Nothing, "WriteObject should not be called more than once for the same object.  Use WriteReference instead")
                    nametable(value) = component.Site.Name
                End If
     
                Dim isControl = TypeOf value Is Control
     
                If isControl Then
                    Dim childAttr = document.CreateAttribute("children")
                    childAttr.Value = "Controls"
                    node.Attributes.Append(childAttr)
                End If
     
                If component IsNot Nothing Then
     
                    If isControl Then
     
                        For Each child As Control In CType(value, Control).Controls
     
                            If child.Site IsNot Nothing AndAlso child.Site.Container Is idh.Container Then
                                node.AppendChild(WriteObject(document, nametable, child))
                            End If
                        Next
                    End If ' if isControl
                    Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(value, propertyAttributes)
     
                    If isControl Then
                        Dim controlProp = properties("Controls")
     
                        If controlProp IsNot Nothing Then
                            Dim propArray = New PropertyDescriptor(properties.Count - 1 - 1) {}
                            Dim idx = 0
     
                            For Each p As PropertyDescriptor In properties
     
                                If p IsNot controlProp Then
                                    propArray(Math.Min(Threading.Interlocked.Increment(idx), idx - 1)) = p
                                End If
                            Next
     
                            properties = New PropertyDescriptorCollection(propArray)
                        End If
                    End If
     
                    WriteProperties(document, properties, value, node, "Property")
                    Dim events As EventDescriptorCollection = TypeDescriptor.GetEvents(value, propertyAttributes)
                    Dim bindings As IEventBindingService = TryCast(host.GetService(GetType(IEventBindingService)), IEventBindingService)
     
                    If bindings IsNot Nothing Then
                        properties = bindings.GetEventProperties(events)
                        WriteProperties(document, properties, value, node, "Event")
                    End If
                Else
                    WriteValue(document, value, node)
                End If
     
                Return node
            End Function
     
            Private Sub WriteProperties(ByVal document As XmlDocument, ByVal properties As PropertyDescriptorCollection, ByVal value As Object, ByVal parent As XmlNode, ByVal elementName As String)
                For Each prop As PropertyDescriptor In properties
     
                    If Equals(prop.Name, "AutoScaleBaseSize") Then
                        Dim _DEBUG_ = prop.Name
                    End If
     
                    If prop.ShouldSerializeValue(value) Then
                        Dim compName = parent.Name
                        Dim node As XmlNode = document.CreateElement(elementName)
                        Dim attr = document.CreateAttribute("name")
                        attr.Value = prop.Name
                        node.Attributes.Append(attr)
                        Dim visibility = CType(prop.Attributes(GetType(DesignerSerializationVisibilityAttribute)), DesignerSerializationVisibilityAttribute)
     
                        Select Case visibility.Visibility
                            Case DesignerSerializationVisibility.Visible
     
                                If Not prop.IsReadOnly AndAlso WriteValue(document, prop.GetValue(value), node) Then
                                    parent.AppendChild(node)
                                End If
     
                            Case DesignerSerializationVisibility.Content
                                Dim propValue = prop.GetValue(value)
     
                                If GetType(IList).IsAssignableFrom(prop.PropertyType) Then
                                    WriteCollection(document, CType(propValue, IList), node)
                                Else
                                    Dim props = TypeDescriptor.GetProperties(propValue, propertyAttributes)
                                    WriteProperties(document, props, propValue, node, elementName)
                                End If
     
                                If node.ChildNodes.Count > 0 Then
                                    parent.AppendChild(node)
                                End If
     
                            Case Else
                        End Select
                    End If
                Next
            End Sub
     
            Private Function WriteReference(ByVal document As XmlDocument, ByVal value As IComponent) As XmlNode
                Dim idh = CType(host.GetService(GetType(IDesignerHost)), IDesignerHost)
                Debug.Assert(value IsNot Nothing AndAlso value.Site IsNot Nothing AndAlso value.Site.Container Is idh.Container, "Invalid component passed to WriteReference")
                Dim node As XmlNode = document.CreateElement("Reference")
                Dim attr = document.CreateAttribute("name")
                attr.Value = value.Site.Name
                node.Attributes.Append(attr)
                Return node
            End Function
            Public LeCode As String
            Private Function WriteValue(ByVal document As XmlDocument, ByVal value As Object, ByVal parent As XmlNode) As Boolean
     
                Dim idh = CType(host.GetService(GetType(IDesignerHost)), IDesignerHost)
     
     
                ' For empty values, we just return.  This creates an empty node.
                If value Is Nothing Then
                    Return True
                End If
     
                Dim converter = TypeDescriptor.GetConverter(value)
     
                If GetConversionSupported(converter, GetType(String)) Then
                    parent.InnerText = CStr(converter.ConvertTo(Nothing, CultureInfo.InvariantCulture, value, GetType(String)))
                ElseIf GetConversionSupported(converter, GetType(Byte())) Then
                    Dim data = CType(converter.ConvertTo(Nothing, CultureInfo.InvariantCulture, value, GetType(Byte())), Byte())
                    parent.AppendChild(WriteBinary(document, data))
                ElseIf GetConversionSupported(converter, GetType(InstanceDescriptor)) Then
                    Dim id = CType(converter.ConvertTo(Nothing, CultureInfo.InvariantCulture, value, GetType(InstanceDescriptor)), InstanceDescriptor)
                    parent.AppendChild(WriteInstanceDescriptor(document, id, value))
                ElseIf TypeOf value Is IComponent AndAlso CType(value, IComponent).Site IsNot Nothing AndAlso CType(value, IComponent).Site.Container Is idh.Container Then
                    parent.AppendChild(WriteReference(document, CType(value, IComponent)))
                ElseIf value.GetType().IsSerializable Then
                    Dim formatter As BinaryFormatter = New BinaryFormatter()
                    Dim stream As MemoryStream = New MemoryStream()
                    formatter.Serialize(stream, value)
                    Dim binaryNode As XmlNode = WriteBinary(document, stream.ToArray())
                    parent.AppendChild(binaryNode)
                Else
                    Return False
                End If
     
                Return True
            End Function
     
            Private Sub WriteCollection(ByVal document As XmlDocument, ByVal list As IList, ByVal parent As XmlNode)
                For Each obj In list
                    Dim node As XmlNode = document.CreateElement("Item")
                    Dim typeAttr = document.CreateAttribute("type")
                    typeAttr.Value = obj.GetType().AssemblyQualifiedName
                    node.Attributes.Append(typeAttr)
                    WriteValue(document, obj, node)
                    parent.AppendChild(node)
                Next
            End Sub
     
            Private Function WriteBinary(ByVal document As XmlDocument, ByVal value As Byte()) As XmlNode
                Dim node As XmlNode = document.CreateElement("Binary")
                node.InnerText = Convert.ToBase64String(value)
                Return node
            End Function
     
            Private Function WriteInstanceDescriptor(ByVal document As XmlDocument, ByVal desc As InstanceDescriptor, ByVal value As Object) As XmlNode
                Dim node As XmlNode = document.CreateElement("InstanceDescriptor")
                Dim formatter As BinaryFormatter = New BinaryFormatter()
                Dim stream As MemoryStream = New MemoryStream()
                formatter.Serialize(stream, desc.MemberInfo)
                Dim memberAttr = document.CreateAttribute("member")
                memberAttr.Value = Convert.ToBase64String(stream.ToArray())
                node.Attributes.Append(memberAttr)
     
                For Each arg In desc.Arguments
                    Dim argNode As XmlNode = document.CreateElement("Argument")
     
                    If WriteValue(document, arg, argNode) Then
                        node.AppendChild(argNode)
                    End If
                Next
     
                If Not desc.IsComplete Then
                    Dim props = TypeDescriptor.GetProperties(value, propertyAttributes)
                    WriteProperties(document, props, value, node, "Property")
                End If
     
                Return node
            End Function
     
     
    #End Region
     
    #Region "DeSerialize - Load"
     
            ''' <summary>
            ''' This method is used to parse the given file.  Before calling this 
            ''' method the host member variable must be setup.  This method will
            ''' create a data set, read the data set from the XML stored in the
            ''' file, and then walk through the data set and create components
            ''' stored within it.  The data set is stored in the persistedData
            ''' member variable upon return.
            ''' 
            ''' This method never throws exceptions.  It will set the successful
            ''' ref parameter to false when there are catastrophic errors it can't
            ''' resolve (like being unable to parse the XML).  All error exceptions
            ''' are added to the errors array list, including minor errors.
            ''' </summary>
            Private Function ReadFile(ByVal fileName As String, ByVal errors As ArrayList, <Out> ByRef document As XmlDocument) As String
                Dim baseClass As String = Nothing
     
     
                ' Anything unexpected is a fatal error.
                '
                Try
                    ' The main form and items in the component tray will be at the
                    ' same level, so we have to create a higher super-root in order
                    ' to construct our XmlDocument.
                    Dim sr As StreamReader = New StreamReader(fileName)
                    Dim cleandown As String = sr.ReadToEnd()
                    cleandown = "<DOCUMENT_ELEMENT>" & cleandown & "</DOCUMENT_ELEMENT>"
                    Dim doc As XmlDocument = New XmlDocument()
                    doc.LoadXml(cleandown)
     
     
                    ' Now, walk through the document's elements.
                    '
                    For Each node As XmlNode In doc.DocumentElement.ChildNodes
     
                        If Equals(baseClass, Nothing) Then
                            baseClass = node.Attributes("name").Value
                        End If
     
                        If node.Name.Equals("Object") Then
                            ReadObject(node, errors)
                        Else
                            errors.Add(String.Format("Node type {0} is not allowed here.", node.Name))
                        End If
                    Next
     
                    document = doc
                Catch ex As Exception
                    document = Nothing
                    errors.Add(ex)
                End Try
     
                Return baseClass
            End Function
     
            Private Sub ReadEvent(ByVal childNode As XmlNode, ByVal instance As Object, ByVal errors As ArrayList)
                Dim bindings As IEventBindingService = TryCast(host.GetService(GetType(IEventBindingService)), IEventBindingService)
     
                If bindings Is Nothing Then
                    errors.Add("Unable to contact event binding service so we can't bind any events")
                    Return
                End If
     
                Dim nameAttr = childNode.Attributes("name")
     
                If nameAttr Is Nothing Then
                    errors.Add("No event name")
                    Return
                End If
     
                Dim methodAttr = childNode.Attributes("method")
     
                If methodAttr Is Nothing OrElse Equals(methodAttr.Value, Nothing) OrElse methodAttr.Value.Length = 0 Then
                    errors.Add(String.Format("Event {0} has no method bound to it"))
                    Return
                End If
     
                Dim evt = TypeDescriptor.GetEvents(instance)(nameAttr.Value)
     
                If evt Is Nothing Then
                    errors.Add(String.Format("Event {0} does not exist on {1}", nameAttr.Value, instance.GetType().FullName))
                    Return
                End If
     
                Dim prop = bindings.GetEventProperty(evt)
                Debug.Assert(prop IsNot Nothing, "Bad event binding service")
     
                Try
                    prop.SetValue(instance, methodAttr.Value)
                Catch ex As Exception
                    errors.Add(ex.Message)
                End Try
            End Sub
     
            Private Function ReadInstanceDescriptor(ByVal node As XmlNode, ByVal errors As ArrayList) As Object
                ' First, need to deserialize the member
                '
                Dim memberAttr = node.Attributes("member")
     
                If memberAttr Is Nothing Then
                    errors.Add("No member attribute on instance descriptor")
                    Return Nothing
                End If
     
                Dim data = Convert.FromBase64String(memberAttr.Value)
                Dim formatter As BinaryFormatter = New BinaryFormatter()
                Dim stream As MemoryStream = New MemoryStream(data)
                Dim mi = CType(formatter.Deserialize(stream), MemberInfo)
                Dim args As Object() = Nothing
     
     
                ' Check to see if this member needs arguments.  If so, gather
                ' them from the XML.
                If TypeOf mi Is MethodBase Then
                    Dim paramInfos As ParameterInfo() = CType(mi, MethodBase).GetParameters()
                    args = New Object(paramInfos.Length - 1) {}
                    Dim idx = 0
     
                    For Each child As XmlNode In node.ChildNodes
     
                        If child.Name.Equals("Argument") Then
                            Dim value As Object
     
                            If Not ReadValue(child, TypeDescriptor.GetConverter(paramInfos(idx).ParameterType), errors, value) Then
                                Return Nothing
                            End If
     
                            args(Math.Min(Threading.Interlocked.Increment(idx), idx - 1)) = value
                        End If
                    Next
     
                    If idx <> paramInfos.Length Then
                        errors.Add(String.Format("Member {0} requires {1} arguments, not {2}.", mi.Name, args.Length, idx))
                        Return Nothing
                    End If
                End If
     
                Dim id As InstanceDescriptor = New InstanceDescriptor(mi, args)
                Dim instance As Object = id.Invoke()
     
     
                ' Ok, we have our object.  Now, check to see if there are any properties, and if there are, 
                ' set them.
                '
                For Each prop As XmlNode In node.ChildNodes
     
                    If prop.Name.Equals("Property") Then
                        ReadProperty(prop, instance, errors)
                    End If
                Next
     
                Return instance
            End Function
     
            ''' Reads the "Object" tags. This returns an instance of the
            ''' newly created object. Returns null if there was an error.
            Private Function ReadObject(ByVal node As XmlNode, ByVal errors As ArrayList) As Object
                Dim typeAttr = node.Attributes("type")
     
                If typeAttr Is Nothing Then
                    errors.Add("<Object> tag is missing required type attribute")
                    Return Nothing
                End If
     
                Dim type = System.Type.GetType(typeAttr.Value)
     
                If type Is Nothing Then
                    errors.Add(String.Format("Type {0} could not be loaded.", typeAttr.Value))
                    Return Nothing
                End If
     
     
                ' This can be null if there is no name for the object.
                '
                Dim nameAttr = node.Attributes("name")
                Dim instance As Object
     
                If GetType(IComponent).IsAssignableFrom(type) Then
     
                    If nameAttr Is Nothing Then
                        instance = host.CreateComponent(type)
                    Else
                        instance = host.CreateComponent(type, nameAttr.Value)
                    End If
                Else
                    instance = Activator.CreateInstance(type)
                End If
     
     
                ' Got an object, now we must process it.  Check to see if this tag
                ' offers a child collection for us to add children to.
                '
                Dim childAttr = node.Attributes("children")
                Dim childList As IList = Nothing
     
                If childAttr IsNot Nothing Then
                    Dim childProp = TypeDescriptor.GetProperties(instance)(childAttr.Value)
     
                    If childProp Is Nothing Then
                        errors.Add(String.Format("The children attribute lists {0} as the child collection but this is not a property on {1}", childAttr.Value, instance.GetType().FullName))
                    Else
                        childList = TryCast(childProp.GetValue(instance), IList)
     
                        If childList Is Nothing Then
                            errors.Add(String.Format("The property {0} was found but did not return a valid IList", childProp.Name))
                        End If
                    End If
                End If
     
     
                ' Now, walk the rest of the tags under this element.
                '
                For Each childNode As XmlNode In node.ChildNodes
     
                    If childNode.Name.Equals("Object") Then
     
                        ' Another object.  In this case, create the object, and
                        ' parent it to ours using the children property.  If there
                        ' is no children property, bail out now.
                        If childAttr Is Nothing Then
                            errors.Add("Child object found but there is no children attribute")
                            Continue For
                        End If
     
     
                        ' no sense doing this if there was an error getting the property.  We've already reported the
                        ' error above.
                        If childList IsNot Nothing Then
                            Dim childInstance = ReadObject(childNode, errors)
                            childList.Add(childInstance)
                        End If
                    ElseIf childNode.Name.Equals("Property") Then
                        ' A property.  Ask the property to parse itself.
                        '
                        ReadProperty(childNode, instance, errors)
                    ElseIf childNode.Name.Equals("Event") Then
                        ' An event.  Ask the event to parse itself.
                        '
                        ReadEvent(childNode, instance, errors)
                    End If
                Next
     
                Return instance
            End Function
     
            ''' Parses the given XML node and sets the resulting property value.
            Private Sub ReadProperty(ByVal node As XmlNode, ByVal instance As Object, ByVal errors As ArrayList)
                Dim nameAttr = node.Attributes("name")
     
                If nameAttr Is Nothing Then
                    errors.Add("Property has no name")
                    Return
                End If
     
                Dim prop = TypeDescriptor.GetProperties(instance)(nameAttr.Value)
     
                If prop Is Nothing Then
                    errors.Add(String.Format("Property {0} does not exist on {1}", nameAttr.Value, instance.GetType().FullName))
                    Return
                End If
     
     
                ' Get the type of this property.  We have three options:
                ' 1.  A normal read/write property.
                ' 2.  A "Content" property.
                ' 3.  A collection.
                '
                Dim isContent = prop.Attributes.Contains(DesignerSerializationVisibilityAttribute.Content)
     
                If isContent Then
                    Dim value = prop.GetValue(instance)
     
     
                    ' Handle the case of a content property that is a collection.
                    '
                    If TypeOf value Is IList Then
     
                        For Each child As XmlNode In node.ChildNodes
     
                            If child.Name.Equals("Item") Then
                                Dim item As Integer
                                Dim typeAttr = child.Attributes("type")
     
                                If typeAttr Is Nothing Then
                                    errors.Add("Item has no type attribute")
                                    Continue For
                                End If
     
                                Dim type = System.Type.GetType(typeAttr.Value)
     
                                If type Is Nothing Then
                                    errors.Add(String.Format("Item type {0} could not be found.", typeAttr.Value))
                                    Continue For
                                End If
     
                                If ReadValue(child, TypeDescriptor.GetConverter(type), errors, item) Then
     
                                    Try
                                        CType(value, IList).Add(item)
                                    Catch ex As Exception
                                        errors.Add(ex.Message)
                                    End Try
                                End If
                            Else
                                errors.Add(String.Format("Only Item elements are allowed in collections, not {0} elements.", child.Name))
                            End If
                        Next
                    Else
     
                        ' Handle the case of a content property that consists of child properties.
                        '
                        For Each child As XmlNode In node.ChildNodes
     
                            If child.Name.Equals("Property") Then
                                ReadProperty(child, value, errors)
                            Else
                                errors.Add(String.Format("Only Property elements are allowed in content properties, not {0} elements.", child.Name))
                            End If
                        Next
                    End If
                Else
                    Dim value As Integer
     
                    If ReadValue(node, prop.Converter, errors, value) Then
     
                        ' ReadValue succeeded.  Fill in the property value.
                        '
                        Try
                            prop.SetValue(instance, value)
                        Catch ex As Exception
                            errors.Add(ex.Message)
                        End Try
                    End If
                End If
            End Sub
     
            ''' Generic function to read an object value.  Returns true if the read
            ''' succeeded.
            Private Function ReadValue(ByVal node As XmlNode, ByVal converter As TypeConverter, ByVal errors As ArrayList, <Out> ByRef value As Object) As Boolean
                Try
     
                    For Each child As XmlNode In node.ChildNodes
     
                        If child.NodeType = XmlNodeType.Text Then
                            value = converter.ConvertFromInvariantString(node.InnerText)
                            Return True
                        ElseIf child.Name.Equals("Binary") Then
                            Dim data = Convert.FromBase64String(child.InnerText)
     
     
                            ' Binary blob.  Now, check to see if the type converter
                            ' can convert it.  If not, use serialization.
                            '
                            If GetConversionSupported(converter, GetType(Byte())) Then
                                value = converter.ConvertFrom(Nothing, CultureInfo.InvariantCulture, data)
                                Return True
                            Else
                                Dim formatter As BinaryFormatter = New BinaryFormatter()
                                Dim stream As MemoryStream = New MemoryStream(data)
                                value = formatter.Deserialize(stream)
                                Return True
                            End If
                        ElseIf child.Name.Equals("InstanceDescriptor") Then
                            value = ReadInstanceDescriptor(child, errors)
                            Return value IsNot Nothing
                        Else
                            errors.Add(String.Format("Unexpected element type {0}", child.Name))
                            value = Nothing
                            Return False
                        End If
                    Next
     
     
                    ' If we get here, it is because there were no nodes.  No nodes and no inner
                    ' text is how we signify null.
                    '
                    value = Nothing
                    Return True
                Catch ex As Exception
                    errors.Add(ex.Message)
                    value = Nothing
                    Return False
                End Try
            End Function
     
     
    #End Region
     
    #Region "Public methods"
     
            ''' This method writes out the contents of our designer in XML.
            ''' It writes out the contents of xmlDocument.
            Public Function GetCode() As String
                Flush()
                Dim sw As StringWriter
                sw = New StringWriter()
                Dim xtw As XmlTextWriter = New XmlTextWriter(sw)
                xtw.Formatting = Formatting.Indented
                xmlDocument.WriteTo(xtw)
                Dim cleanup As String = sw.ToString().Replace("<DOCUMENT_ELEMENT>", "")
                cleanup = cleanup.Replace("</DOCUMENT_ELEMENT>", "")
                sw.Close()
                Return cleanup
            End Function
     
            Public Sub Save()
                Save(False)
            End Sub
     
     
            ''' <summary>
            ''' Save the current state of the loader. If the user loaded the file
            ''' or saved once before, then he doesn't need to select a file again.
            ''' Unless this is being called as a result of "Save As..." being clicked,
            ''' in which case forceFilePrompt will be true.
            ''' </summary>
     
            Public Sub Save(ByVal forceFilePrompt As Boolean)
                Try
                    Flush()
                    Dim filterIndex = 3
     
                    If Equals(fileName, Nothing) OrElse forceFilePrompt Then
                        Dim dlg As SaveFileDialog = New SaveFileDialog()
                        dlg.DefaultExt = "xml"
                        dlg.Filter = "XML Files|*.xml"
     
                        If dlg.ShowDialog() = DialogResult.OK Then
                            fileName = dlg.FileName
     
                            filterIndex = dlg.FilterIndex
     
                        End If
                    End If
     
                    If Not Equals(fileName, Nothing) Then
     
                        Select Case filterIndex
                            Case 1
                                ' Write out our xmlDocument to a file.
                                Dim sw As StringWriter = New StringWriter()
                                Dim xtw As XmlTextWriter = New XmlTextWriter(sw)
                                xtw.Formatting = Formatting.Indented
                                xmlDocument.WriteTo(xtw)
     
                                ' Get rid of our artificial super-root before we save out
                                ' the XML.
                                '
                                Dim cleanup As String = sw.ToString().Replace("<DOCUMENT_ELEMENT>", "")
                                cleanup = cleanup.Replace("</DOCUMENT_ELEMENT>", "")
                                xtw.Close()
                                Dim file As StreamWriter = New StreamWriter(fileName)
                                file.Write(cleanup)
                                file.Close()
                        End Select
     
                        unsaved = False
                    End If
     
                Catch ex As Exception
                    MessageBox.Show("Error during save: " & ex.ToString())
                End Try
            End Sub
    #End Region
     
        End Class ' class
    End Namespace ' namespace

    La classe HostSurface.vb

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    Imports System
    Imports System.Collections
    Imports System.ComponentModel
    Imports System.ComponentModel.Design
    Imports System.ComponentModel.Design.Serialization
    Imports System.Drawing
    Imports System.Windows.Forms
    Imports System.Diagnostics
    Imports DevComponents.DotNetBar
     
    Namespace OSMaker
        ''' <summary>
        ''' Inherits from DesignSurface and hosts the RootComponent and 
        ''' all other designers. It also uses loaders (BasicDesignerLoader
        ''' or CodeDomDesignerLoader) when required. It also provides various
        ''' services to the designers. Adds MenuCommandService which is used
        ''' for Cut, Copy, Paste, etc.
        ''' </summary>
        Public Class HostSurface
            Inherits DesignSurface
     
            Private _loader As BasicDesignerLoader
            Private _selectionService As ISelectionService
     
            Public Sub New()
                MyBase.New()
                AddService(GetType(IMenuCommandService), New MenuCommandService(Me))
            End Sub
     
            Public Sub New(ByVal parentProvider As IServiceProvider)
                MyBase.New(parentProvider)
                AddService(GetType(IMenuCommandService), New MenuCommandService(Me))
            End Sub
     
            Friend Sub Initialize()
                Dim control As Control = Nothing
                Dim host = CType(GetService(GetType(IDesignerHost)), IDesignerHost)
     
                If host Is Nothing Then Return
     
                Try
                    ' Set the backcolor
                    Dim hostType As Type = host.RootComponent.GetType()
     
                    If hostType Is GetType(Form) Then
                        control = TryCast(View, Control)
                        control.BackColor = System.Drawing.Color.FromArgb(CType(CType(30, Byte), Integer), CType(CType(30, Byte), Integer), CType(CType(30, Byte), Integer))
                        control.Dock = DockStyle.Fill
                    ElseIf hostType Is GetType(UserControl) Then
                        control = TryCast(View, Control)
                        control.BackColor = Color.White
                    ElseIf hostType Is GetType(Component) Then
                        control = TryCast(View, Control)
                        control.BackColor = Color.FloralWhite
                    Else
                        Throw New Exception("Undefined Host Type: " & hostType.ToString())
                    End If
     
     
                    ' Set SelectionService - SelectionChanged event handler
                    _selectionService = CType(ServiceContainer.GetService(GetType(ISelectionService)), ISelectionService)
                    AddHandler _selectionService.SelectionChanged, New EventHandler(AddressOf selectionService_SelectionChanged)
                Catch ex As Exception
                    Trace.WriteLine(ex.ToString())
                End Try
            End Sub
     
            Public Property Loader As BasicDesignerLoader
                Get
                    Return _loader
                End Get
                Set(ByVal value As BasicDesignerLoader)
                    _loader = value
                End Set
            End Property
     
     
            ''' <summary>
            ''' When the selection changes this sets the PropertyGrid's selected component 
            ''' </summary>
            Private Sub selectionService_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
                If _selectionService IsNot Nothing Then
                    Dim selectedComponents As ICollection = _selectionService.GetSelectedComponents()
                    Dim propertyGrid = CType(GetService(GetType(DevComponents.DotNetBar.AdvPropertyGrid)), DevComponents.DotNetBar.AdvPropertyGrid)
                    Dim comps = New Object(selectedComponents.Count - 1) {}
                    Dim i = 0
     
                    For Each o In selectedComponents
                        comps(i) = o
                        i += 1
                    Next
     
                    propertyGrid.SelectedObjects = comps
     
                End If
            End Sub
     
            Public Sub AddService(ByVal type As Type, ByVal serviceInstance As Object)
                ServiceContainer.AddService(type, serviceInstance)
            End Sub
        End Class ' class
    End Namespace ' namespace
    Control utilisateur HostControl.vb

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    Imports System
    Imports System.ComponentModel
    Imports System.ComponentModel.Design
    Imports System.Drawing
    Imports System.Windows.Forms
    Imports System.Diagnostics
     
    Namespace OSMaker
        ''' <summary>
        ''' Hosts the HostSurface which inherits from DesignSurface.
        ''' </summary>
        Public Class HostControl
            Inherits UserControl
     
            ''' <summary>
            ''' Required designer variable.
            ''' </summary>
            Private components As IContainer = Nothing
            Private _hostSurface As HostSurface
            Private _hostSurfaceManager As HostSurfaceManager
     
            Friend Sub New(ByVal hostSurface As HostSurface)
                ' This call is required by the Windows.Forms Form Designer.
                InitializeComponent()
                InitializeHost(hostSurface)
            End Sub
     
     
            ''' <summary>
            ''' Clean up any resources being used.
            ''' </summary>
            Protected Overrides Sub Dispose(ByVal disposing As Boolean)
                If disposing Then
                    If components IsNot Nothing Then components.Dispose()
                End If
     
                MyBase.Dispose(disposing)
            End Sub
     
     
    #Region "Component Designer generated code"
            ''' <summary>
            ''' Required method for Designer support - do not modify 
            ''' the contents of this method with the code editor.
            ''' </summary>
            Private Sub InitializeComponent()
                Me.ContextMenuBar1 = New DevComponents.DotNetBar.ContextMenuBar()
                Me.ButtonItem1 = New DevComponents.DotNetBar.ButtonItem()
                Me.ButtonItem2 = New DevComponents.DotNetBar.ButtonItem()
                Me.ButtonItem3 = New DevComponents.DotNetBar.ButtonItem()
                CType(Me.ContextMenuBar1, System.ComponentModel.ISupportInitialize).BeginInit()
                Me.SuspendLayout()
                '
                'ContextMenuBar1
                '
                Me.ContextMenuBar1.AntiAlias = True
                Me.ContextMenuBar1.Font = New System.Drawing.Font("Segoe UI", 9.0!)
                Me.ContextMenuBar1.IsMaximized = False
                Me.ContextMenuBar1.Items.AddRange(New DevComponents.DotNetBar.BaseItem() {Me.ButtonItem1})
                Me.ContextMenuBar1.Location = New System.Drawing.Point(331, 211)
                Me.ContextMenuBar1.Name = "ContextMenuBar1"
                Me.ContextMenuBar1.Size = New System.Drawing.Size(75, 25)
                Me.ContextMenuBar1.Stretch = True
                Me.ContextMenuBar1.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled
                Me.ContextMenuBar1.TabIndex = 0
                Me.ContextMenuBar1.TabStop = False
                Me.ContextMenuBar1.Text = "ContextMenuBar1"
                '
                'ButtonItem1
                '
                Me.ButtonItem1.AutoExpandOnClick = True
                Me.ButtonItem1.Name = "ButtonItem1"
                Me.ButtonItem1.SubItems.AddRange(New DevComponents.DotNetBar.BaseItem() {Me.ButtonItem2, Me.ButtonItem3})
                Me.ButtonItem1.Text = "ButtonItem1"
                '
                'ButtonItem2
                '
                Me.ButtonItem2.Name = "ButtonItem2"
                Me.ButtonItem2.Text = "ButtonItem2"
                '
                'ButtonItem3
                '
                Me.ButtonItem3.Name = "ButtonItem3"
                Me.ButtonItem3.Text = "ButtonItem3"
                '
                'HostControl
                '
                Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(30, Byte), Integer), CType(CType(30, Byte), Integer), CType(CType(30, Byte), Integer))
                Me.ContextMenuBar1.SetContextMenuEx(Me, Me.ButtonItem1)
                Me.Controls.Add(Me.ContextMenuBar1)
                Me.Name = "HostControl"
                Me.Size = New System.Drawing.Size(484, 346)
                CType(Me.ContextMenuBar1, System.ComponentModel.ISupportInitialize).EndInit()
                Me.ResumeLayout(False)
     
            End Sub
     
    #End Region
     
            Friend Sub InitializeHost(ByVal hostSurface As HostSurface)
                Try
                    If hostSurface Is Nothing Then Return
                    _hostSurface = hostSurface
     
                    Dim Control As Control = TryCast(_hostSurface.View, Control)
     
                    Control.Parent = Me
                    Control.Dock = DockStyle.Fill
                    Control.Visible = True
     
                Catch ex As Exception
                    Trace.WriteLine(ex.ToString())
                End Try
            End Sub
     
            Friend ReadOnly Property HostSurface As HostSurface
                Get
                    Return _hostSurface
                End Get
            End Property
            Public Class codee
     
            End Class
     
     
            Friend ReadOnly Property DesignerHost As IDesignerHost
                Get
                    Return CType(_hostSurface.GetService(GetType(IDesignerHost)), IDesignerHost)
                End Get
            End Property
     
            Private Sub HostControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
     
                Me.Dock = DockStyle.Fill
     
            End Sub
     
            Private Sub Timer1_Tick(sender As Object, e As EventArgs)
     
     
            End Sub
     
            Friend WithEvents ContextMenuBar1 As DevComponents.DotNetBar.ContextMenuBar
            Friend WithEvents ButtonItem1 As DevComponents.DotNetBar.ButtonItem
            Friend WithEvents ButtonItem2 As DevComponents.DotNetBar.ButtonItem
            Friend WithEvents ButtonItem3 As DevComponents.DotNetBar.ButtonItem
        End Class ' class
    End Namespace ' namespace
    Hostsurfacemanager.vb
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    Imports System
    Imports System.ComponentModel
    Imports System.ComponentModel.Design
    Imports System.ComponentModel.Design.Serialization
    Imports System.Windows.Forms
    Imports System.IO
    Imports System.Windows.Forms.Design
     
    Imports System.CodeDom
     
     
    Namespace OSMaker
        Public Enum LoaderType
            BasicDesignerLoader = 1
            CodeDomDesignerLoader = 2
            NoLoader = 3
        End Enum
     
     
        ''' <summary>
        ''' Manages numerous HostSurfaces. Any services added to HostSurfaceManager
        ''' will be accessible to all HostSurfaces
        ''' </summary>
        Friend Class HostSurfaceManager
            Inherits DesignSurfaceManager
     
            Public Sub New()
                MyBase.New()
                AddService(GetType(INameCreationService), New NameCreationService())
                AddHandler ActiveDesignSurfaceChanged, New ActiveDesignSurfaceChangedEventHandler(AddressOf HostSurfaceManager_ActiveDesignSurfaceChanged)
            End Sub
     
            Protected Overrides Function CreateDesignSurfaceCore(ByVal parentProvider As IServiceProvider) As DesignSurface
                Return New HostSurface(parentProvider)
     
            End Function
     
     
            ''' <summary>
            ''' Gets a new HostSurface and loads it with the appropriate type of
            ''' root component. 
            ''' </summary>
            Private Function GetNewHost(ByVal rootComponentType As Type) As HostControl
                Dim hostSurface = CType(CreateDesignSurface(ServiceContainer), HostSurface)
     
     
                If rootComponentType Is GetType(Form) Then
                    hostSurface.BeginLoad(GetType(Form))
                ElseIf rootComponentType Is GetType(UserControl) Then
                    hostSurface.BeginLoad(GetType(UserControl))
                ElseIf rootComponentType Is GetType(Component) Then
                    hostSurface.BeginLoad(GetType(Component))
                ElseIf rootComponentType Is GetType(MyTopLevelComponent) Then
                    hostSurface.BeginLoad(GetType(MyTopLevelComponent))
                Else
                    Throw New Exception("Undefined Host Type: " & rootComponentType.ToString())
                End If
     
                hostSurface.Initialize()
                ActiveDesignSurface = hostSurface
                Return New HostControl(hostSurface)
            End Function
     
     
            ''' <summary>
            ''' Gets a new HostSurface and loads it with the appropriate type of
            ''' root component. Uses the appropriate Loader to load the HostSurface.
            ''' </summary>
            Public Function GetNewHost(ByVal rootComponentType As Type, ByVal loaderType As LoaderType) As HostControl
                If loaderType = LoaderType.NoLoader Then Return GetNewHost(rootComponentType)
                Dim hostSurface = CType(CreateDesignSurface(ServiceContainer), HostSurface)
                Dim host = CType(hostSurface.GetService(GetType(IDesignerHost)), IDesignerHost)
     
                Select Case loaderType
     
                    Case LoaderType.BasicDesignerLoader
                        Dim basicHostLoader As Loader.BasicHostLoader = New Loader.BasicHostLoader(rootComponentType)
                        hostSurface.BeginLoad(basicHostLoader)
                        hostSurface.Loader = basicHostLoader
                    Case LoaderType.CodeDomDesignerLoader
                        Dim codeDomHostLoader As Loader.CodeDomHostLoader = New Loader.CodeDomHostLoader()
                        hostSurface.BeginLoad(codeDomHostLoader)
                        hostSurface.Loader = codeDomHostLoader
                    Case Else
                        Throw New Exception("Loader is not defined: " & loaderType.ToString())
                End Select
     
                hostSurface.Initialize()
                Return New HostControl(hostSurface)
            End Function
     
     
            ''' <summary>
            ''' Opens an Xml file and loads it up using BasicHostLoader (inherits from
            ''' BasicDesignerLoader)
            ''' </summary>
            Public Function GetNewHost(ByVal fileName As String) As HostControl
                If Equals(fileName, Nothing) OrElse Not File.Exists(fileName) Then MessageBox.Show("FileName is incorrect: " & fileName)
                Dim loaderType As LoaderType = LoaderType.NoLoader
                If fileName.EndsWith("xml") Then loaderType = LoaderType.BasicDesignerLoader
     
                If loaderType = LoaderType.NoLoader OrElse loaderType = LoaderType.CodeDomDesignerLoader Then
                    Throw New Exception("File cannot be opened. Please check the type or extension of the file. Supported format is Xml")
                End If
     
                Dim hostSurface = CType(CreateDesignSurface(ServiceContainer), HostSurface)
                Dim host = CType(hostSurface.GetService(GetType(IDesignerHost)), IDesignerHost)
     
                Dim basicHostLoader As Loader.BasicHostLoader = New Loader.BasicHostLoader(fileName)
     
                hostSurface.BeginLoad(basicHostLoader)
                hostSurface.Loader = basicHostLoader
                hostSurface.Initialize()
                Return New HostControl(hostSurface)
            End Function
     
            Public Sub AddService(ByVal type As Type, ByVal serviceInstance As Object)
                ServiceContainer.AddService(type, serviceInstance)
     
            End Sub
     
     
            ''' <summary>
            ''' Uses the OutputWindow service and writes out to it.
            ''' </summary>
            Private Sub HostSurfaceManager_ActiveDesignSurfaceChanged(ByVal sender As Object, ByVal e As ActiveDesignSurfaceChangedEventArgs)
                ' Dim o As ToolWindows.OutputWindow = TryCast(GetService(GetType(ToolWindows.OutputWindow)), ToolWindows.OutputWindow)
                'o.RichTextBox.Text += "New host added." & Microsoft.VisualBasic.Constants.vbLf
            End Sub
        End Class ' class
    End Namespace ' namespace
    Comment faire pour implémenter un ContextMenuStrip (couper,copier,coller,undo,redo,premier plan...) sur le concepteur et surtout faire fonctionner les autres commande que seulement delete la seule qui fonctionne actuellement? J'ai essayé de m'aider de la source https://github.com/veler/SoftwareZat...teurFenetre.vb mais je n'ai pas réussi.

    voici une doc en C# https://docs.microsoft.com/fr-fr/dot...ew=netcore-3.1

    Je vous remercie pour votre aide en C# ou en VB.Net

  2. #2
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour
    En convertissant le code du Shell en question du c# vers vb.net ,tu as du loupé quelque chose ou beaucoup de choses car le Shell en question :
    - utilise un MainMenu (et ses MainMenuItem enfants) qu'il suffit de substituer par un ContextMenuStrip

    -toutes les commandes Cut,Paste,Delete etc...du Shell fonctionne comme des charmes.

    Ton devoir est à revoir ...

  3. #3
    Nouveau membre du Club Avatar de M.Leroy
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2019
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Février 2019
    Messages : 49
    Points : 31
    Points
    31
    Par défaut
    Bonjour je reprend le relais de mon collaborateur,
    les fichiers vb.net sont traduits mot pour mot , peut-être que ça fonctionne avec les autres loader (codedom) mais quand on sélectionne basichostloader dans le projet Shell on remarque que le menu Edit n'est plus cliquable (peut-être un signe que ce n'est pas codé pour Basichostloader dans le projet Schell) . Même en C# les commandes copy,paste etc ne fonctionnent pas mais encore une fois le problème ne viens pas de la traduction, simplement du fait que je ne parvient pas à coder ce qu'il faut pour.
    Merci

  4. #4
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    rebonjour

    Mr Le Roi (je plaisante) , mais la littérature Microsoft est toujours verbeuse sur ce
    le sujet dit du "DesignerHost" et j'allais dire foireuse(articles MSDN)
    Je suis maintenant amplement convaincu concernant l'article (mentionné) qui a été certainement produit par un "nègre"(pigiste hindoue) des articles MSDN.
    Lorsque j'ai consulte la MSDN Lib Fr (edition complete de VS 2008).
    J'ai trouve ce bref article :
    Knowledge Base

    INFO: Code Sample That Demonstrates How to Create a Custom Form Designer by Using Visual C# .NET
    This article contains a code sample that demonstrates how to create a custom form designer by using Microsoft Visual C# .NET. Microsoft does not provide Microsoft Product Support Services or support hotfixes for this code sample.
    lien de téléchargement du "designerhost" mentionné ci-dessus:
    http://download.microsoft.com/downlo...signerhost.exe

    Eh bien ce "designerhost" est un vrai razoir d’Occam :
    - il comporte un seul "loader"
    - mais "serialize" et édite les trois type de fichier source : codedom .cs,.vb et miraculous xml
    - sauvegarde également les trois type de fichier source

    - peut recharger un projet sauvegarde quelque soit le source(.cs,.vb ou xml)
    - gère cut,copy,paste et delete sur la surface de designer (un Form par défaut est créé grâce au menu New)

    Comment cela se peut-il ?
    Eh bien le "DesignerHost" fait appel à 2 services de serialization :
    -l'habituel CodeDomComponentSerializationService
    -& un "custom serializer" qui broie tout même les controls dont le code original figurant dans le lien de telechargement est donné ci après:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Design.Serialization;
    using System.ComponentModel.Design;
    using System.Collections;
    using System.Windows.Forms;
     
    namespace SampleDesignerApplication
    {
        class DesignerSerializationServiceImpl : IDesignerSerializationService
        {
            private IServiceContainer serviceProvider=null;
     
            public DesignerSerializationServiceImpl(IServiceContainer serviceContainer)
            {
                serviceProvider = serviceContainer;
            }
            public System.Collections.ICollection Deserialize(object serializationData)
            {
     
                 return this.Deserialize(serializationData);
            }
     
            public object Serialize(System.Collections.ICollection objects)
            {
     
                return this.Serialize(objects);
     
            }
        }
    }


    Mais ce code du "custom serializer" est bogué car il entre dans une boucle infinie qui finit dans un "stackoverflow" pénible des qu'on clique sur les commandes de menu "Cut" ou "Copy"
    il convient donc de le remplacer par ce qui suit(revu et corrigé) :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Design.Serialization;
    using System.ComponentModel.Design;
    using System.Collections;
    using System.Windows.Forms;
     
    namespace SampleDesignerApplication
    {
        class DesignerSerializationServiceImpl : IDesignerSerializationService
        {
            private IServiceContainer serviceProvider=null;
     
            public DesignerSerializationServiceImpl(IServiceContainer serviceContainer)
            {
                serviceProvider = serviceContainer;
            }
            public System.Collections.ICollection Deserialize(object serializationData)
            {
                SerializationStore serializationStore = serializationData as SerializationStore;
     
                if (serializationStore != null)
                {
     
                    ComponentSerializationService componentSerializationService = serviceProvider.GetService(typeof(ComponentSerializationService)) as ComponentSerializationService;
     
                    ICollection collection = componentSerializationService.Deserialize(serializationStore);
     
                    return collection;
     
                }
     
                return new object[0];
     
                //return this.Deserialize(serializationData);
            }
     
            public object Serialize(System.Collections.ICollection objects)
            {
                ComponentSerializationService componentSerializationService = serviceProvider.GetService(typeof(ComponentSerializationService)) as ComponentSerializationService;
     
                SerializationStore returnObject = null;
                using (SerializationStore serializationStore = componentSerializationService.CreateStore())
                {
                    foreach (object obj in objects)
                    {
                        if (obj is Control)
                        {
                            componentSerializationService.Serialize(serializationStore, obj);
                        }
     
                    }
     
                    returnObject = serializationStore;
     
                }
     
                return returnObject;
                //return this.Serialize(objects);
     
            }
        }
    }
    On peut parfois être induit sur une fausse route par des "codeurs" du dimanche mais il ne faut jamais renoncer à ses objectifs.

    En espérant que Le Roi sera satisfait ce soir.
    Bon design.

Discussions similaires

  1. Réponses: 4
    Dernier message: 24/02/2009, 12h06
  2. [power designer et Sybase] trigger
    Par mr_qno dans le forum Sybase
    Réponses: 4
    Dernier message: 12/07/2006, 18h32
  3. [OpenTools, designer] CmtSubComponent et superClasse
    Par kainor dans le forum JBuilder
    Réponses: 4
    Dernier message: 04/03/2003, 11h32
  4. Réponses: 3
    Dernier message: 09/02/2003, 01h09
  5. Désigner une variable avec une variable?
    Par littleman dans le forum Paradox
    Réponses: 4
    Dernier message: 12/08/2002, 11h21

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo