‘Flag Attribute for Enum’s

        

// Utilizar VStudio 2010 Beta 2, con este código.

‘// El propósito de este código es mostrar el uso 
‘// de los indicadores de enumeraciones utilizando
‘// conversiones hexadecimales (por ejemplo!).
‘//
‘// (c)(r) 🙂 PepLluis 2009

‘// Para entender este ejemplo, imagina que
‘// necesitas controlar algún dispositivo, ya sea
‘// a través de Ethernet, USB o Puerto Serie, para
‘// Supervisar or controlar las operaciones de
‘// paro o marcha, trabando solo con dos bytes…
‘// el primero de ellos mapeando los bits de
‘// salida y el segundo los de entrada, después
‘// de esto solo necesitaras enviar el byte de
‘// salida al dispositivo o supervisar la entrada
‘// cuando se produzca un cambio en su valor.

‘// Este ejemplo además muestra el uso de
‘// la continuación implícita de línea y los
‘// inicializadores para poder añadir todos los
‘// Controles necesarios en el form, en un solo
‘// golpe.
.

‘// Los comentarios y el código están en Ingles
‘// por tema de difusión, no dudes en pedírmelos
‘// en Castellano, si lo consideras oportuno

‘// Test this code with Visual Studio 2010 Beta 2.

‘// the purpose of this code is just show and play ‘// with flag’s enumerations and play using
‘// hexadecimals conversions.
‘//
‘// (C)(R) 🙂 PepLluis 2009

‘// To understand this sample… imagine you need
‘// control some devices using Ethernet, USB or
‘// Serial Ports to supervise and set/reset their
‘// status with start/stop operations, just two
‘// bytes… the first one to map input bits
‘// and the second to map output bits, after
‘// this you only need send output byte to device
‘// or supervise received byte when value change.

‘// this sample also show how use implicit line
‘// continuation and initializers to add controls
‘// in one shot in load event (for example).

 

 

Y aqui el Codigo…

‘Define input channel
<FlagsAttribute()> Public Enum InputChannel
    PowerAlarm = 1
    LowVoltage = 2
    HighVoltage = 4
    OverCurrent = 8
    PowerGood = 16
    ShortCircuit = 32
    WithoutLoad = 64
    OutOfService = 128
End Enum

» Define output channel
<FlagsAttribute()> Public Enum OutputChannel
    Engine_Axis1 = 1
    Engine_Axis2 = 2
    Engine_Axis3 = 4
    Smoke_Vent = 8
    Refrigerator = 16
    Blast_Furnace = 32
    TransPort_Belt = 64
    Emergency_Stop = 128
End Enum

‘// You can add dynamically items to enum and no changes are needed inside code… just rebuild

Public Class FlagsEnumerationSample
    Private Sub When_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ‘Title
        Me.Text = «Playing with Flag’s Enum’s»
        ‘Add all labels and textbox in one shot
        Me.Controls.AddRange({New Label With {.Name = «lblHexcaptn»,
                                              .AutoSize = True,
                                              .Location = New Point(5, 10),
                                              .Text = «Output Value:»},
                              New Label With {.Name = «lblHexValue»,
                                              .AutoSize = True,
                                              .Location = New Point(75, 10),
                                              .Text = «0x00», .Height = 20},
                              New Label With {.Name = «lblInputVal»,
                                              .AutoSize = True,
                                              .Location = New Point(140, 10),
                                              .Text = «Input Value : 0x»},
                              New TextBox With {.Name = «txtInputVal»,
                                                .MaxLength = 2,
                                                .Width = 20,
                                                .Location = New Point(220, 8),
                                                .Text = «00»}
                            })

        ‘Add one customized button for every item in enumeration
        Dim NextPos As Integer = 30                                             ‘Point for this button (30=initial top pos)
        For Each elem In [Enum].GetValues(GetType(OutputChannel))               ‘iterate output enum
            Me.Controls.Add(New CustomButton(New Point(20, NextPos), elem))     ‘add new button with new point position for elem
            AddHandler Me.Controls(elem.ToString).Click, AddressOf OutPutOnOff  ‘When button is click put output on/off
            NextPos += Me.Controls(elem.ToString).Height                        ‘Calculate next point location for next elem
        Next

        NextPos = 30                                                            ‘Initial top pos for first element
        For Each elem In [Enum].GetValues(GetType(InputChannel))                ‘Iterate input enum
            Me.Controls.Add(New CustomLabel(New Point(160, NextPos), elem))     ‘Add customized label for any bit input in enum
            NextPos += Me.Controls(elem.ToString).Height                        ‘Calculate location for next label
        Next
        ‘Simulate input value… refresh labels when textbox value change
        AddHandler Me.Controls(«txtInputVal»).TextChanged, AddressOf InputsOnOff

        Me.Height = NextPos + 50                                                ‘Fix form height, after last control + 50
    End Sub

    Private Outputs As Byte = 0                                                 ‘Output channel (Byte)
   
    ‘Change On/Off output bit status of sender
    ‘remark : TAG property of button is used as bit weight
    Sub OutPutOnOff(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If Outputs And CType(sender, Button).Tag Then                           ‘Flic /Flac output bit
            Outputs = Outputs Xor CType(sender, Button).Tag                     ‘Set Off if On
            sender.BackColor = Color.GreenYellow                                ‘GreenYellow if Off
        Else
            Outputs = Outputs Or CType(sender, Button).Tag                      ‘Set On if Off
            sender.BackColor = Color.Red                                        ‘Reed if On
        End If
        Me.Controls(«lblHexValue»).Text = «0x» + Hex(Outputs)
    End Sub

    Private Inputs As Byte? = 0                                                 ‘Input channel (Byte)
    ‘Change color of label when bit is On or Off
    ‘remark : TAG property of label is used as bit weight
    Sub InputsOnOff()
        Try
            Inputs = «&h0» + Me.Controls(«txtInputVal»).Text                    ‘Read & convert text as Hex value
        Catch ex As Exception
            Me.Controls(«txtInputVal»).Text = «»                                ‘Wrong format… clear textbox
        End Try

        For Each Elem In [Enum].GetNames(GetType(InputChannel))                 ‘for each item in enum
            If Inputs And CType(Me.Controls(Elem), Label).Tag Then              ‘Red Color if bit is On, Green if off
                Me.Controls(Elem).BackColor = Color.Red
            Else
                Me.Controls(Elem).BackColor = Color.GreenYellow
            End If
        Next
    End Sub
End
Class


‘ Just My customizes Button to select and display outputs
Class CustomButton
    Inherits Button
   
    ‘ Create using
       _location inside form
       _elem     particular item of enumeration
    Sub New(ByVal _location As Point, ByVal _elem As [Enum])
        Me.Tag = CType(_elem, OutputChannel)                    ‘My Bit weight
        Me.Name = _elem.ToString                                ‘My Name
        Me.Text = Me.Name                                       ‘Name to Show
        Me.Width = 100                                          ‘Wide
        Me.Location = _location                                 ‘Set Position
        Me.BackColor = Color.GreenYellow                        ‘Initial Color
    End Sub
End
Class


‘ Just My customized Label to display Inputs
Class CustomLabel
    Inherits Label
   
    ‘ Create using
       _location pos inside form
       _elem     particular item of enumeration
    Sub New(ByVal _location As Point, ByVal _elem As [Enum])
        Me.Tag = CType(_elem, InputChannel)                     ‘My Bit weight
        Me.Name = _elem.ToString                                ‘My Name
        Me.Text = Me.Name                                       ‘Name to Show
        Me.Width = 100                                          ‘Wide
        Me.Location = _location                                 ‘Position
        Me.TextAlign = ContentAlignment.MiddleCenter            ‘Align
        Me.BackColor = Color.GreenYellow                        ‘Initial color
        Me.BorderStyle = Windows.Forms.BorderStyle.FixedSingle  ‘Set Border
    End Sub
End
Class

Salud,
Pep Lluis,

Un pensamiento en “‘Flag Attribute for Enum’s”

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *