elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado: AIO elhacker.NET 2021 Compilación herramientas análisis y desinfección malware


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 5 Visitantes están viendo este tema.
Páginas: 1 ... 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 [60] Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 556,862 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.926



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #590 en: 26 Abril 2024, 18:38 pm »

Comparto una forma que he ideado para automatizar la traducción, al idioma actual de la aplicación, los valores booleanos en un propertygrid (por ejemplo), mediante el uso clases de atributos.







El modo de empleo es muy sencillo:

Código
  1. public class TestClass
  2.  
  3. <LocalizableBoolean>
  4. <TypeConverter(GetType(LocalizableBooleanConverter))>
  5. Public Property FeatureEnabled As Boolean = True
  6.  
  7. end class

Código
  1. Me.PropertyGrid1.SelectedObject = new TestClass()

También se puede utilizar de esta forma alternativa para una representación arbitraria en los idiomas que se especifiquen mediante un string separado por comas (en este ejemplo, el español y el francés):

Código
  1. <LocalizableBoolean("es, fr", "ssssí!!, Oui!", "nope!, Non!")>
  2. <TypeConverter(GetType(LocalizableBooleanConverter))>
  3. Public Property FeatureEnabled As Boolean = True





El código:

LocalizedBoolean.vb
Código
  1. ''' <summary>
  2. ''' Represents localized strings for <see langword="True"/> and <see langword="False"/> <see cref="Boolean"/> values.
  3. ''' </summary>
  4. <DebuggerStepThrough>
  5. Public NotInheritable Class LocalizedBoolean
  6.  
  7.    ''' <summary>
  8.    ''' The <see cref="CultureInfo"/> that represents the region for
  9.    ''' the localized strings in <see cref="LocalizedBoolean.True"/>
  10.    ''' and <see cref="LocalizedBoolean.False"/> properties.
  11.    ''' </summary>
  12.    Public ReadOnly Property Culture As CultureInfo
  13.  
  14.    ''' <summary>
  15.    ''' The localized string representation for <see langword="True"/> <see cref="Boolean"/> value.
  16.    ''' </summary>
  17.    Public ReadOnly Property [True] As String
  18.  
  19.    ''' <summary>
  20.    ''' The localized string representation for <see langword="False"/> <see cref="Boolean"/> value.
  21.    ''' </summary>
  22.    Public ReadOnly Property [False] As String
  23.  
  24.    ''' <summary>
  25.    ''' Initializes a new instance of the <see cref="LocalizedBoolean"/> class.
  26.    ''' </summary>
  27.    '''
  28.    ''' <param name="culture">
  29.    ''' The <see cref="CultureInfo"/> that represents the region for the localized strings.
  30.    ''' </param>
  31.    '''
  32.    ''' <param name="trueString">
  33.    ''' The localized string representation for <see langword="True"/> <see cref="Boolean"/> value.
  34.    ''' </param>
  35.    '''
  36.    ''' <param name="falseString">
  37.    ''' The localized string representation for <see langword="False"/> <see cref="Boolean"/> value.
  38.    ''' </param>
  39.    Public Sub New(culture As CultureInfo, trueString As String, falseString As String)
  40.        If culture Is Nothing Then
  41.            Throw New ArgumentNullException(paramName:=NameOf(culture))
  42.        End If
  43.        If String.IsNullOrWhiteSpace(trueString) Then
  44.            Throw New ArgumentNullException(paramName:=NameOf(trueString))
  45.        End If
  46.        If String.IsNullOrWhiteSpace(falseString) Then
  47.            Throw New ArgumentNullException(paramName:=NameOf(falseString))
  48.        End If
  49.  
  50.        Me.Culture = culture
  51.        Me.True = trueString
  52.        Me.False = falseString
  53.    End Sub
  54.  
  55.    ''' <summary>
  56.    ''' Prevents a default instance of the <see cref="LocalizedBoolean"/> class from being created.
  57.    ''' </summary>
  58.    Private Sub New()
  59.    End Sub
  60.  
  61. End Class

LocalizableBooleanAttribute.vb
Código:
''' <summary>
''' Specifies that a <see cref="Boolean"/> property can display localized string representations
''' for <see langword="True"/> and <see langword="False"/> values.
''' </summary>
<AttributeUsage(AttributeTargets.Property, AllowMultiple:=False, Inherited:=True)>
<DebuggerStepThrough>
Public NotInheritable Class LocalizableBooleanAttribute : Inherits Attribute

    ''' <summary>
    ''' Gets the localized boolean representations.
    ''' <para></para>
    ''' The dictionary Key is the ISO 639-1 two-letter code for the language.
    ''' </summary>
    Public ReadOnly Property Localizations As Dictionary(Of String, LocalizedBoolean)

    ''' <summary>
    ''' Initializes a new instance of the <see cref="LocalizedBoolean"/> class.
    ''' </summary>
    Public Sub New()
        Me.Localizations = New Dictionary(Of String, LocalizedBoolean)(StringComparison.OrdinalIgnoreCase) From {
            {"af", New LocalizedBoolean(CultureInfo.GetCultureInfo("af"), "Ja", "Nee")}, ' Afrikaans
            {"am", New LocalizedBoolean(CultureInfo.GetCultureInfo("am"), "እወዳለሁ", "አይደለሁ")}, ' Amharic
            {"ar", New LocalizedBoolean(CultureInfo.GetCultureInfo("ar"), "نعم", "لا")}, ' Arabic
            {"az", New LocalizedBoolean(CultureInfo.GetCultureInfo("az"), "Bəli", "Xeyr")}, ' Azerbaijani
            {"be", New LocalizedBoolean(CultureInfo.GetCultureInfo("be"), "Так", "Не")}, ' Belarusian
            {"bg", New LocalizedBoolean(CultureInfo.GetCultureInfo("bg"), "Да", "Не")}, ' Bulgarian
            {"bn", New LocalizedBoolean(CultureInfo.GetCultureInfo("bn"), "হ্যাঁ", "না")}, ' Bengali
            {"ca", New LocalizedBoolean(CultureInfo.GetCultureInfo("ca"), "Sí", "No")}, ' Catalan
            {"cs", New LocalizedBoolean(CultureInfo.GetCultureInfo("cs"), "Ano", "Ne")}, ' Czech
            {"cy", New LocalizedBoolean(CultureInfo.GetCultureInfo("cy"), "Ie", "Na")}, ' Welsh
            {"da", New LocalizedBoolean(CultureInfo.GetCultureInfo("da"), "Ja", "Nej")}, ' Danish
            {"de", New LocalizedBoolean(CultureInfo.GetCultureInfo("de"), "Ja", "Nein")}, ' German
            {"el", New LocalizedBoolean(CultureInfo.GetCultureInfo("el"), "Ναι", "Όχι")}, ' Greek
            {"en", New LocalizedBoolean(CultureInfo.GetCultureInfo("en"), "Yes", "No")}, ' English
            {"es", New LocalizedBoolean(CultureInfo.GetCultureInfo("es"), "Sí", "No")}, ' Spanish
            {"et", New LocalizedBoolean(CultureInfo.GetCultureInfo("et"), "Jah", "Ei")}, ' Estonian
            {"eu", New LocalizedBoolean(CultureInfo.GetCultureInfo("eu"), "Bai", "Ez")}, ' Basque
            {"fa", New LocalizedBoolean(CultureInfo.GetCultureInfo("fa"), "بله", "خیر")}, ' Persian
            {"fi", New LocalizedBoolean(CultureInfo.GetCultureInfo("fi"), "Kyllä", "Ei")}, ' Finnish
            {"fr", New LocalizedBoolean(CultureInfo.GetCultureInfo("fr"), "Oui", "Non")}, ' French
            {"ga", New LocalizedBoolean(CultureInfo.GetCultureInfo("ga"), "Tá", "Níl")}, ' Irish
            {"gd", New LocalizedBoolean(CultureInfo.GetCultureInfo("gd"), "Tha", "Chan eil")}, ' Scottish Gaelic
            {"gl", New LocalizedBoolean(CultureInfo.GetCultureInfo("gl"), "Si", "Non")}, ' Galician
            {"gu", New LocalizedBoolean(CultureInfo.GetCultureInfo("gu"), "હા", "ના")}, ' Gujarati
            {"hi", New LocalizedBoolean(CultureInfo.GetCultureInfo("hi"), "हाँ", "नहीं")}, ' Hindi
            {"hr", New LocalizedBoolean(CultureInfo.GetCultureInfo("hr"), "Da", "Ne")}, ' Croatian
            {"ht", New LocalizedBoolean(CultureInfo.GetCultureInfo("ht"), "Wi", "Pa")}, ' Haitian Creole
            {"hu", New LocalizedBoolean(CultureInfo.GetCultureInfo("hu"), "Igen", "Nem")}, ' Hungarian
            {"id", New LocalizedBoolean(CultureInfo.GetCultureInfo("id"), "Ya", "Tidak")}, ' Indonesian
            {"ig", New LocalizedBoolean(CultureInfo.GetCultureInfo("ig"), "Ee", "Mba")}, ' Igbo
            {"is", New LocalizedBoolean(CultureInfo.GetCultureInfo("is"), "Já", "Nei")}, ' Icelandic
            {"it", New LocalizedBoolean(CultureInfo.GetCultureInfo("it"), "Sì", "No")}, ' Italian
            {"ja", New LocalizedBoolean(CultureInfo.GetCultureInfo("ja"), "はい", "いいえ")}, ' Japanese
            {"jv", New LocalizedBoolean(CultureInfo.GetCultureInfo("jv"), "Iya", "Ora")}, ' Javanese
            {"kk", New LocalizedBoolean(CultureInfo.GetCultureInfo("kk"), "Иә", "Жоқ")}, ' Kazakh
            {"km", New LocalizedBoolean(CultureInfo.GetCultureInfo("km"), "បាទ/ចាស", "ទេ")}, ' Khmer
            {"kn", New LocalizedBoolean(CultureInfo.GetCultureInfo("kn"), "ಹೌದು", "ಇಲ್ಲ")}, ' Kannada
            {"ko", New LocalizedBoolean(CultureInfo.GetCultureInfo("ko"), "예", "아니오")}, ' Korean
            {"ku", New LocalizedBoolean(CultureInfo.GetCultureInfo("ku"), "Belê", "Na")}, ' Kurdish (Kurmanji)
            {"ky", New LocalizedBoolean(CultureInfo.GetCultureInfo("ky"), "Ооба", "Жок")}, ' Kyrgyz
            {"la", New LocalizedBoolean(CultureInfo.GetCultureInfo("la"), "Ita", "Non")}, ' Latin
            {"lg", New LocalizedBoolean(CultureInfo.GetCultureInfo("lg"), "Yee", "Nedda")}, ' Luganda
            {"lt", New LocalizedBoolean(CultureInfo.GetCultureInfo("lt"), "Taip", "Ne")}, ' Lithuanian
            {"lv", New LocalizedBoolean(CultureInfo.GetCultureInfo("lv"), "Jā", "Nē")}, ' Latvian
            {"mg", New LocalizedBoolean(CultureInfo.GetCultureInfo("mg"), "Eny", "Tsia")}, ' Malagasy
            {"mi", New LocalizedBoolean(CultureInfo.GetCultureInfo("mi"), "Āe", "Kāo")}, ' Maori
            {"mk", New LocalizedBoolean(CultureInfo.GetCultureInfo("mk"), "Да", "Не")}, ' Macedonian
            {"ml", New LocalizedBoolean(CultureInfo.GetCultureInfo("ml"), "അതെ", "ഇല്ല")}, ' Malayalam
            {"mn", New LocalizedBoolean(CultureInfo.GetCultureInfo("mn"), "Тийм", "Үгүй")}, ' Mongolian
            {"mr", New LocalizedBoolean(CultureInfo.GetCultureInfo("mr"), "होय", "नाही")}, ' Marathi
            {"ms", New LocalizedBoolean(CultureInfo.GetCultureInfo("ms"), "Ya", "Tidak")}, ' Malay
            {"mt", New LocalizedBoolean(CultureInfo.GetCultureInfo("mt"), "Iva", "Le")}, ' Maltese
            {"my", New LocalizedBoolean(CultureInfo.GetCultureInfo("my"), "ဟုတ်ကဲ့", "မဟုတ်ဘူး")}, ' Burmese
            {"ne", New LocalizedBoolean(CultureInfo.GetCultureInfo("ne"), "हो", "होइन")}, ' Nepali
            {"nl", New LocalizedBoolean(CultureInfo.GetCultureInfo("nl"), "Ja", "Nee")}, ' Dutch
            {"no", New LocalizedBoolean(CultureInfo.GetCultureInfo("no"), "Ja", "Nei")}, ' Norwegian
            {"ny", New LocalizedBoolean(CultureInfo.GetCultureInfo("ny"), "Yewo", "Ayawo")}, ' Chichewa
            {"pa", New LocalizedBoolean(CultureInfo.GetCultureInfo("pa"), "ਹਾਂ", "ਨਹੀਂ")}, ' Punjabi
            {"pl", New LocalizedBoolean(CultureInfo.GetCultureInfo("pl"), "Tak", "Nie")}, ' Polish
            {"ps", New LocalizedBoolean(CultureInfo.GetCultureInfo("ps"), "هو", "نه")}, ' Pashto
            {"pt", New LocalizedBoolean(CultureInfo.GetCultureInfo("pt"), "Sim", "Não")}, ' Portuguese
            {"rm", New LocalizedBoolean(CultureInfo.GetCultureInfo("rm"), "Gia", "Betg")}, ' Romansh
            {"ro", New LocalizedBoolean(CultureInfo.GetCultureInfo("ro"), "Da", "Nu")}, ' Romanian
            {"ru", New LocalizedBoolean(CultureInfo.GetCultureInfo("ru"), "Да", "Нет")}, ' Russian
            {"sd", New LocalizedBoolean(CultureInfo.GetCultureInfo("sd"), "هاڻي", "نه")}, ' Sindhi
            {"si", New LocalizedBoolean(CultureInfo.GetCultureInfo("si"), "ඔව්", "නැත")}, ' Sinhala
            {"sk", New LocalizedBoolean(CultureInfo.GetCultureInfo("sk"), "Áno", "Nie")}, ' Slovak
            {"sl", New LocalizedBoolean(CultureInfo.GetCultureInfo("sl"), "Da", "Ne")}, ' Slovenian
            {"sm", New LocalizedBoolean(CultureInfo.GetCultureInfo("sm"), "Ioe", "Leai")}, ' Samoan
            {"sn", New LocalizedBoolean(CultureInfo.GetCultureInfo("sn"), "Yebo", "Cha")}, ' Shona
            {"so", New LocalizedBoolean(CultureInfo.GetCultureInfo("so"), "Haa", "Maya")}, ' Somali
            {"sq", New LocalizedBoolean(CultureInfo.GetCultureInfo("sq"), "Po", "Jo")}, ' Albanian
            {"sr", New LocalizedBoolean(CultureInfo.GetCultureInfo("sr"), "Да", "Не")}, ' Serbian (Cyrillic)
            {"su", New LocalizedBoolean(CultureInfo.GetCultureInfo("su"), "Iya", "Teu")}, ' Sundanese
            {"sv", New LocalizedBoolean(CultureInfo.GetCultureInfo("sv"), "Ja", "Nej")}, ' Swedish
            {"sw", New LocalizedBoolean(CultureInfo.GetCultureInfo("sw"), "Ndiyo", "Hapana")}, ' Swahili
            {"ta", New LocalizedBoolean(CultureInfo.GetCultureInfo("ta"), "ஆம்", "இல்லை")}, ' Tamil
            {"te", New LocalizedBoolean(CultureInfo.GetCultureInfo("te"), "అవును", "కాదు")}, ' Telugu
            {"tg", New LocalizedBoolean(CultureInfo.GetCultureInfo("tg"), "Ҳа", "Не")}, ' Tajik
            {"th", New LocalizedBoolean(CultureInfo.GetCultureInfo("th"), "ใช่", "ไม่")}, ' Thai
            {"ti", New LocalizedBoolean(CultureInfo.GetCultureInfo("ti"), "እወ", "አይወ")}, ' Tigrinya
            {"tk", New LocalizedBoolean(CultureInfo.GetCultureInfo("tk"), "Hawa", "Ýok")}, ' Turkmen
            {"to", New LocalizedBoolean(CultureInfo.GetCultureInfo("to"), "ʻIo", "ʻEa")}, ' Tongan
            {"tr", New LocalizedBoolean(CultureInfo.GetCultureInfo("tr"), "Evet", "Hayır")}, ' Turkish
            {"tt", New LocalizedBoolean(CultureInfo.GetCultureInfo("tt"), "Әйе", "Юк")}, ' Tatar
            {"ug", New LocalizedBoolean(CultureInfo.GetCultureInfo("ug"), "ھەئە", "ياق")}, ' Uighur
            {"uk", New LocalizedBoolean(CultureInfo.GetCultureInfo("uk"), "Так", "Ні")}, ' Ukrainian
            {"ur", New LocalizedBoolean(CultureInfo.GetCultureInfo("ur"), "جی ہاں", "نہیں")}, ' Urdu
            {"uz", New LocalizedBoolean(CultureInfo.GetCultureInfo("uz"), "Ha", "Yo'q")}, ' Uzbek
            {"vi", New LocalizedBoolean(CultureInfo.GetCultureInfo("vi"), "Có", "Không")}, ' Vietnamese
            {"xh", New LocalizedBoolean(CultureInfo.GetCultureInfo("xh"), "Ewe", "Hayi")}, ' Xhosa
            {"yi", New LocalizedBoolean(CultureInfo.GetCultureInfo("yi"), "יאָ", "ניי")}, ' Yiddish
            {"yo", New LocalizedBoolean(CultureInfo.GetCultureInfo("yo"), "Bẹẹni", "Bẹẹkoo")}, ' Yoruba
            {"zh", New LocalizedBoolean(CultureInfo.GetCultureInfo("zh"), "是", "不")}, ' Chinese (Simplified)
            {"zu", New LocalizedBoolean(CultureInfo.GetCultureInfo("zu"), "Yebo", "Cha")} ' Zulu
        }
    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="LocalizedBoolean"/> class.
    ''' </summary>
    '''
    ''' <param name="cultureNames">
    ''' A comma-separated value of the ISO 639-1 two-letter code languages (e.g.: "en,es,fr").
    ''' </param>
    '''
    ''' <param name="trueStrings">
    ''' A comma-separated value of the localized string representation for "True" boolean value (e.g.: "Yes,Sí,Oui").
    ''' </param>
    '''
    ''' <param name="falseStrings">
    ''' A comma-separated value of the localized string representation for "False" boolean value (e.g.: "No,No,Non").
    ''' </param>
    Public Sub New(cultureNames As String, trueStrings As String, falseStrings As String)
        Me.New()

        If String.IsNullOrWhiteSpace(cultureNames) Then
            Throw New ArgumentNullException(paramName:=NameOf(cultureNames))
        End If
        If String.IsNullOrWhiteSpace(trueStrings) Then
            Throw New ArgumentNullException(paramName:=NameOf(trueStrings))
        End If
        If String.IsNullOrWhiteSpace(falseStrings) Then
            Throw New ArgumentNullException(paramName:=NameOf(falseStrings))
        End If

        Dim cultureNamesArray As String() = cultureNames.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
        Dim trueStringsArray As String() = trueStrings.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
        Dim falseStringsArray As String() = falseStrings.Split({","c}, StringSplitOptions.RemoveEmptyEntries)

        If cultureNamesArray.Length <> trueStringsArray.Length OrElse cultureNamesArray.Length <> falseStringsArray.Length Then
            Throw New InvalidOperationException("The comma-separated values must have the same amount of tokens.")
        End If

        For i As Integer = 0 To cultureNamesArray.Length - 1
            Dim cultureName As String = cultureNamesArray(i).Trim()
            Dim trueString As String = trueStringsArray(i).Trim()
            Dim falseString As String = falseStringsArray(i).Trim()

            If cultureName.Length <> 2 Then
                Throw New InvalidOperationException("The culture name must be a ISO 639-1 two-letter code.")
            End If

            Dim localizedBoolean As New LocalizedBoolean(CultureInfo.GetCultureInfo(cultureName), trueString, falseString)
            If Me.Localizations.ContainsKey(cultureName) Then
                Me.Localizations(cultureName) = localizedBoolean
            Else
                Me.Localizations.Add(cultureName, localizedBoolean)
            End If
        Next
    End Sub

End Class

LocalizableBooleanConverter.vb
Código
  1. ''' <summary>
  2. ''' Provides conversion functionality between Boolean values and localized strings representing "True" and "False" boolean values.
  3. ''' </summary>
  4. Public Class LocalizableBooleanConverter : Inherits TypeConverter
  5.  
  6.    ''' <summary>
  7.    ''' The localized string representation for "True" boolean value.
  8.    ''' </summary>
  9.    Private trueString As String = "Yes"
  10.  
  11.    ''' <summary>
  12.    ''' The localized string representation for "False" boolean value.
  13.    ''' </summary>
  14.    Private falseString As String = "No"
  15.  
  16.    ''' <summary>
  17.    ''' Returns whether this converter can convert an object of the given type to the type of this converter,
  18.    ''' using the specified context.
  19.    ''' </summary>
  20.    '''
  21.    ''' <param name="context">
  22.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  23.    ''' </param>
  24.    '''
  25.    ''' <param name="sourceType">
  26.    ''' A <see cref="Type" /> that represents the type you want to convert from.
  27.    ''' </param>
  28.    '''
  29.    ''' <returns>
  30.    ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  31.    ''' </returns>
  32.    Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
  33.  
  34.        Return sourceType = GetType(String) OrElse MyBase.CanConvertFrom(context, sourceType)
  35.  
  36.    End Function
  37.  
  38.    ''' <summary>
  39.    ''' Returns whether this converter can convert the object to the specified type, using the specified context.
  40.    ''' </summary>
  41.    '''
  42.    ''' <param name="context">
  43.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  44.    ''' </param>
  45.    '''
  46.    ''' <param name="destinationType">
  47.    ''' A <see cref="Type"/> that represents the type you want to convert to.
  48.    ''' </param>
  49.    '''
  50.    ''' <returns>
  51.    ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  52.    ''' </returns>
  53.    Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
  54.  
  55.        Return destinationType = GetType(String) OrElse MyBase.CanConvertTo(context, destinationType)
  56.  
  57.    End Function
  58.  
  59.    ''' <summary>
  60.    ''' Converts the given object to the type of this converter, using the specified context and culture information.
  61.    ''' </summary>
  62.    '''
  63.    ''' <param name="context">
  64.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  65.    ''' </param>
  66.    '''
  67.    ''' <param name="culture">
  68.    ''' The <see cref="CultureInfo"/> to use as the current culture.
  69.    ''' </param>
  70.    '''
  71.    ''' <param name="value">
  72.    ''' The <see cref="Object"/> to convert.
  73.    ''' </param>
  74.    '''
  75.    ''' <returns>
  76.    ''' An <see cref="Object"/> that represents the converted value.
  77.    ''' </returns>
  78.    <DebuggerStepperBoundary>
  79.    Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As Globalization.CultureInfo, value As Object) As Object
  80.  
  81.        If TypeOf value Is String Then
  82.            Dim stringValue As String = DirectCast(value, String)
  83.            If String.Equals(stringValue, Me.trueString, StringComparison.OrdinalIgnoreCase) Then
  84.                Return True
  85.            ElseIf String.Equals(stringValue, Me.FalseString, StringComparison.OrdinalIgnoreCase) Then
  86.                Return False
  87.            End If
  88.        End If
  89.  
  90.        Return MyBase.ConvertFrom(context, culture, value)
  91.  
  92.    End Function
  93.  
  94.    ''' <summary>
  95.    ''' Converts the given value object to the specified type, using the specified context and culture information.
  96.    ''' </summary>
  97.    '''
  98.    ''' <param name="context">
  99.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  100.    ''' </param>
  101.    '''
  102.    ''' <param name="culture">
  103.    ''' A <see cref="CultureInfo"/>. If null is passed, the current culture is assumed.
  104.    ''' </param>
  105.    '''
  106.    ''' <param name="value">
  107.    ''' The <see cref="Object"/> to convert.
  108.    ''' </param>
  109.    '''
  110.    ''' <param name="destinationType">
  111.    ''' The <see cref="Type"/> to convert the <paramref name="value"/> parameter to.
  112.    ''' </param>
  113.    '''
  114.    ''' <returns>
  115.    ''' An <see cref="Object"/> that represents the converted value.
  116.    ''' </returns>
  117.    <DebuggerStepperBoundary>
  118.    Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As Globalization.CultureInfo, value As Object, destinationType As Type) As Object
  119.  
  120.        If context IsNot Nothing Then
  121.            Dim attributes As IEnumerable(Of LocalizableBooleanAttribute) =
  122.                context.PropertyDescriptor.Attributes.OfType(Of LocalizableBooleanAttribute)
  123.  
  124.            For Each attr As LocalizableBooleanAttribute In attributes
  125.                Dim uiCulture As CultureInfo = My.Application.UICulture
  126.                Dim localizedBoolean As LocalizedBoolean = Nothing
  127.                If attr.Localizations.ContainsKey(uiCulture.TwoLetterISOLanguageName) Then
  128.                    localizedBoolean = attr.Localizations(uiCulture.TwoLetterISOLanguageName)
  129.                End If
  130.  
  131.                If localizedBoolean IsNot Nothing Then
  132.                    Me.trueString = localizedBoolean.True
  133.                    Me.falseString = localizedBoolean.False
  134.                End If
  135.            Next
  136.        End If
  137.  
  138.        If destinationType = GetType(String) Then
  139.            If TypeOf value Is Boolean Then
  140.                Dim boolValue As Boolean = value
  141.                Return If(boolValue, Me.trueString, Me.falseString)
  142.            End If
  143.        End If
  144.  
  145.        Return MyBase.ConvertTo(context, culture, value, destinationType)
  146.  
  147.    End Function
  148.  
  149.    ''' <summary>
  150.    ''' Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.
  151.    ''' </summary>
  152.    '''
  153.    ''' <param name="context">
  154.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context that can be used to
  155.    ''' extract additional information about the environment from which this converter is invoked.
  156.    ''' <para></para>
  157.    ''' This parameter or properties of this parameter can be null.
  158.    ''' </param>
  159.    '''
  160.    ''' <returns>
  161.    ''' A <see cref="StandardValuesCollection"/> that holds a standard set of valid values,
  162.    ''' or <see langword="null" /> if the data type does not support a standard set of values.
  163.    ''' </returns>
  164.    Public Overrides Function GetStandardValues(context As ITypeDescriptorContext) As StandardValuesCollection
  165.  
  166.        Return New StandardValuesCollection(New Boolean() {True, False})
  167.  
  168.    End Function
  169.  
  170.    ''' <summary>
  171.    ''' Returns whether this object supports a standard set of values that can be picked from a list, using the specified context.
  172.    ''' </summary>
  173.    '''
  174.    ''' <param name="context">
  175.    ''' An <see cref="ITypeDescriptorContext" /> that provides a format context.
  176.    ''' </param>
  177.    '''
  178.    ''' <returns>
  179.    ''' <see langword="True"/> if <see cref="TypeConverter.GetStandardValues"/> should be called to
  180.    ''' find a common set of values the object supports; otherwise, <see langword="False"/>.
  181.    ''' </returns>
  182.    Public Overrides Function GetStandardValuesSupported(context As ITypeDescriptorContext) As Boolean
  183.  
  184.        Return True
  185.  
  186.    End Function
  187.  
  188. End Class

NOTA: El diccionario con los idiomas y sus equivalentes para "Sí" y "No", lo ha generado ChatGPT. Puede haber fallos en las traducciones, o en los códigos ISO 639-1 de dos letras. Además, faltaría añadir muchos más idiomas: https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes


« Última modificación: 26 Abril 2024, 21:30 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.926



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #591 en: 27 Abril 2024, 01:20 am »

Comparto otro type converter, para convertir los nombres de los valores de una Enum, a una representación amistosa para mostrarlos, por ejemplo, en un propertygrid.

Este convertidor está optimizado para nombres de enumeración escritos en upper/lower snake case y upper/lower camel case.

Las palabras se separan con un espacio en blanco convencional, y los guiones bajos se reemplazan por un espacio en blanco unicode.

Ejemplo de uso:

Código
  1. <TypeConverter(GetType(EnumNameFormatterConverter))>
  2. Public Enum TestEnum
  3.    MyUpperCamelCaseName
  4.    myLowerCamelCaseName
  5.    My_Upper_Snake_Case_Name
  6.    my_lower_snake_case_name
  7.  
  8.    MyMixed_value123_WTF456wtf_
  9.  
  10.    ___rare_case_STRANGE_Name___________123_aZ_Az_4_5_6_
  11. End Enum

Código
  1. <DefaultValue(TestEnum.MyUpperCamelCaseName)>
  2. Public Property Test As TestEnum = TestEnum.MyUpperCamelCaseName

Sin formato:


Con formato:




El código:

EnumNameFormatterConverter.vb
Código
  1. Imports System.ComponentModel
  2. Imports System.Globalization
  3. Imports System.Runtime.InteropServices
  4. Imports System.Text
  5.  
  6. ''' <summary>
  7. ''' Provides conversion functionality between the value names of an <see cref="[Enum]"/> to a friendly string representation.
  8. ''' <para></para>
  9. ''' This converter is optimized for enum names written in either upper/lower snake case or upper/lower camel case:
  10. ''' <list type="bullet">
  11. '''     <item><description>Snake case: Each word is separated by underscores (e.g.: "My_Value").</description></item>
  12. '''     <item><description>Camel case: Each word is separated by a capitalized letter (e.g.: "MyValue").</description></item>
  13. ''' </list>
  14. ''' </summary>
  15. Public NotInheritable Class EnumNameFormatterConverter : Inherits EnumConverter
  16.  
  17.    ''' <summary>
  18.    ''' Initializes a new instance of the <see cref="EnumNameFormatterConverter"/> class.
  19.    ''' </summary>
  20.    ''' <param name="type">A <see cref="T:System.Type" /> that represents the type of enumeration to associate with this enumeration converter.</param>
  21.    Public Sub New(type As Type)
  22.        MyBase.New(type)
  23.    End Sub
  24.  
  25.    ''' <summary>
  26.    ''' Returns whether this converter can convert an object of the given type to the type of this converter,
  27.    ''' using the specified context.
  28.    ''' </summary>
  29.    '''
  30.    ''' <param name="context">
  31.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  32.    ''' </param>
  33.    '''
  34.    ''' <param name="sourceType">
  35.    ''' A <see cref="Type" /> that represents the type you want to convert from.
  36.    ''' </param>
  37.    '''
  38.    ''' <returns>
  39.    ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  40.    ''' </returns>
  41.    Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
  42.  
  43.        Return sourceType Is GetType(String) OrElse
  44.               MyBase.CanConvertFrom(context, sourceType)
  45.  
  46.    End Function
  47.  
  48.    ''' <summary>
  49.    ''' Returns whether this converter can convert the object to the specified type, using the specified context.
  50.    ''' </summary>
  51.    '''
  52.    ''' <param name="context">
  53.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  54.    ''' </param>
  55.    '''
  56.    ''' <param name="destinationType">
  57.    ''' A <see cref="Type"/> that represents the type you want to convert to.
  58.    ''' </param>
  59.    '''
  60.    ''' <returns>
  61.    ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  62.    ''' </returns>
  63.    Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
  64.  
  65.        Return destinationType Is GetType(String) OrElse
  66.               MyBase.CanConvertTo(context, destinationType)
  67.  
  68.    End Function
  69.  
  70.    ''' <summary>
  71.    ''' Converts the given object to the type of this converter, using the specified context and culture information.
  72.    ''' </summary>
  73.    '''
  74.    ''' <param name="context">
  75.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  76.    ''' </param>
  77.    '''
  78.    ''' <param name="culture">
  79.    ''' The <see cref="CultureInfo"/> to use as the current culture.
  80.    ''' </param>
  81.    '''
  82.    ''' <param name="value">
  83.    ''' The <see cref="Object"/> to convert.
  84.    ''' </param>
  85.    '''
  86.    ''' <returns>
  87.    ''' An <see cref="Object"/> that represents the converted value.
  88.    ''' </returns>
  89.    <DebuggerStepThrough>
  90.    Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object
  91.  
  92.        If TypeOf value Is String Then
  93.            value = DirectCast(value, String).Replace(" ", "").Replace(Convert.ToChar(&H205F), "_"c)
  94.            Return [Enum].Parse(Me.EnumType, value, ignoreCase:=True)
  95.        End If
  96.  
  97.        Return MyBase.ConvertFrom(context, culture, value)
  98.  
  99.    End Function
  100.  
  101.    ''' <summary>
  102.    ''' Converts the given value object to the specified type, using the specified context and culture information.
  103.    ''' </summary>
  104.    '''
  105.    ''' <param name="context">
  106.    ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  107.    ''' </param>
  108.    '''
  109.    ''' <param name="culture">
  110.    ''' A <see cref="CultureInfo"/>. If null is passed, the current culture is assumed.
  111.    ''' </param>
  112.    '''
  113.    ''' <param name="value">
  114.    ''' The <see cref="Object"/> to convert.
  115.    ''' </param>
  116.    '''
  117.    ''' <param name="destinationType">
  118.    ''' The <see cref="Type"/> to convert the <paramref name="value"/> parameter to.
  119.    ''' </param>
  120.    '''
  121.    ''' <returns>
  122.    ''' An <see cref="Object"/> that represents the converted value.
  123.    ''' </returns>
  124.    <DebuggerStepThrough>
  125.    Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object
  126.  
  127.        If destinationType = GetType(String) Then
  128.            Dim name As String = [Enum].GetName(value.GetType(), value)
  129.            If Not String.IsNullOrEmpty(name) Then
  130.                Return Me.FormatName(name)
  131.            End If
  132.        End If
  133.  
  134.        Return MyBase.ConvertTo(context, culture, value, destinationType)
  135.  
  136.    End Function
  137.  
  138.    ''' <summary>
  139.    ''' Formats the name of a <see cref="[Enum]"/> value to a friendly name.
  140.    ''' </summary>
  141.    '''
  142.    ''' <param name="name">
  143.    ''' <see cref="[Enum]"/> value name.
  144.    ''' </param>
  145.    '''
  146.    ''' <returns>
  147.    ''' The resulting friendly name.
  148.    ''' </returns>
  149.    <DebuggerStepThrough>
  150.    Private Function FormatName(name As String) As String
  151.        Dim sb As New StringBuilder()
  152.        Dim previousChar As Char
  153.        Dim previousCharIsWhiteSpace As Boolean
  154.        Dim previousCharIsUpperLetter As Boolean
  155.        Dim previousCharIsDigit As Boolean
  156.        Dim lastParsedCharIsUnderscore As Boolean
  157.        Dim firstCapitalizedLetterIsAdded As Boolean
  158.  
  159.        For i As Integer = 0 To name.Length - 1
  160.            Dim c As Char = name(i)
  161.            If i = 0 Then
  162.                If c.Equals("_"c) Then
  163.                    sb.Append(Convert.ToChar(Convert.ToChar(&H205F)))
  164.                    lastParsedCharIsUnderscore = True
  165.                Else
  166.                    sb.Append(Char.ToUpper(c))
  167.                    firstCapitalizedLetterIsAdded = True
  168.                End If
  169.                Continue For
  170.            End If
  171.  
  172.            previousChar = sb.Chars(sb.Length - 1)
  173.            previousCharIsWhiteSpace = previousChar.Equals(" "c) OrElse previousChar.Equals(Convert.ToChar(&H205F))
  174.            previousCharIsUpperLetter = Char.IsUpper(previousChar)
  175.            previousCharIsDigit = Char.IsDigit(previousChar)
  176.  
  177.            If Char.IsLetter(c) Then
  178.                If previousCharIsDigit AndAlso Not previousCharIsWhiteSpace Then
  179.                    sb.Append(" "c)
  180.                End If
  181.  
  182.                If Char.IsUpper(c) Then
  183.                    If previousCharIsUpperLetter Then
  184.                        sb.Append(c)
  185.                    ElseIf Not previousCharIsWhiteSpace Then
  186.                        sb.Append(" "c)
  187.                        sb.Append(c)
  188.                    Else
  189.                        sb.Append(c)
  190.                    End If
  191.                    firstCapitalizedLetterIsAdded = True
  192.  
  193.                Else
  194.                    If Not firstCapitalizedLetterIsAdded Then
  195.                        sb.Append(Char.ToUpper(c))
  196.                        firstCapitalizedLetterIsAdded = True
  197.                    Else
  198.                        sb.Append(c)
  199.                    End If
  200.  
  201.                End If
  202.  
  203.            ElseIf Char.IsDigit(c) Then
  204.                If Not previousCharIsDigit AndAlso Not previousCharIsWhiteSpace Then
  205.                    sb.Append(" "c)
  206.                End If
  207.                sb.Append(c)
  208.  
  209.            ElseIf c.Equals("_"c) Then
  210.                If lastParsedCharIsUnderscore OrElse Not previousCharIsWhiteSpace Then
  211.                    sb.Append(Convert.ToChar(&H205F)) ' Unicode white-space: "&#8195;"
  212.                    lastParsedCharIsUnderscore = True
  213.                End If
  214.  
  215.            Else
  216.                sb.Append(c)
  217.                lastParsedCharIsUnderscore = False
  218.  
  219.            End If
  220.  
  221.        Next i
  222.  
  223.        Return sb.ToString()
  224.    End Function
  225.  
  226. End Class
  227.  


« Última modificación: 27 Abril 2024, 03:05 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.926



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #592 en: 27 Abril 2024, 03:03 am »

Comparto un enfoque y uso alternativo al código que he publicado arriba. Este enfoque nos permite atribuir nombres específicos a una enumeración para mostrarlos en un property grid.

Modo de empleo:

Código
  1. Imports System.Componentmodel
  2.  
  3. <TypeConverter(GetType(EnumDescriptionConverter))>
  4. Public Enum TestEnum
  5.    <Description("My Upper Camel Case Name")> MyUpperCamelCaseName = 1
  6.    <Description("My Lower Camel Case Name")> myLowerCamelCaseName = 2
  7.    <Description("My Upper Snake Case Name")> My_Upper_Snake_Case_Name = 3
  8.    <Description("My lower snake case Name")> my_lower_snake_case_Name = 4
  9.    <Description("My Mixed value 123 QWERTY 456 wtf_")> MyMixed_value123_QWERTY456wtf_ = 5
  10.    <Description("Rare case STRANGE Name 123 aZ Az 456")> ___rare_case_STRANGE_Name___________123_aZ_Az_4_5_6_ = 6
  11. End Enum

Código
  1. <DefaultValue(TestEnum.MyUpperCamelCaseName)>
  2. Public Property Test As TestEnum = TestEnum.MyUpperCamelCaseName

El código:

Código
  1. Imports System.ComponentModel
  2. Imports System.Globalization
  3. Imports System.Reflection
  4.  
  5. Public NotInheritable Class EnumDescriptionConverter : Inherits EnumConverter
  6.  
  7. ''' <summary>
  8. ''' Initializes a new instance of the <see cref="EnumDescriptionConverter"/> class.
  9. ''' </summary>
  10. ''' <param name="type">A <see cref="T:System.Type" /> that represents the type of enumeration to associate with this enumeration converter.</param>
  11. Public Sub New(type As Type)
  12. MyBase.New(type)
  13. End Sub
  14.  
  15. ''' <summary>
  16. ''' Returns whether this converter can convert the object to the specified type, using the specified context.
  17. ''' </summary>
  18. '''
  19. ''' <param name="context">
  20. ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  21. ''' </param>
  22. '''
  23. ''' <param name="destinationType">
  24. ''' A <see cref="Type"/> that represents the type you want to convert to.
  25. ''' </param>
  26. '''
  27. ''' <returns>
  28. ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  29. ''' </returns>
  30. Public Overrides Function CanConvertTo(context As ITypeDescriptorContext, destinationType As Type) As Boolean
  31.  
  32. Return destinationType Is GetType(String) OrElse
  33.   MyBase.CanConvertTo(context, destinationType)
  34.  
  35. End Function
  36.  
  37. ''' <summary>
  38. ''' Returns whether this converter can convert an object of the given type to the type of this converter,
  39. ''' using the specified context.
  40. ''' </summary>
  41. '''
  42. ''' <param name="context">
  43. ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  44. ''' </param>
  45. '''
  46. ''' <param name="sourceType">
  47. ''' A <see cref="Type" /> that represents the type you want to convert from.
  48. ''' </param>
  49. '''
  50. ''' <returns>
  51. ''' <see langword="True"/> if this converter can perform the conversion; otherwise, <see langword="False"/>.
  52. ''' </returns>
  53. Public Overrides Function CanConvertFrom(context As ITypeDescriptorContext, sourceType As Type) As Boolean
  54.  
  55. Return sourceType Is GetType(String) OrElse
  56.   MyBase.CanConvertFrom(context, sourceType)
  57.  
  58. End Function
  59.  
  60. ''' <summary>
  61. ''' Converts the given value object to the specified type, using the specified context and culture information.
  62. ''' </summary>
  63. '''
  64. ''' <param name="context">
  65. ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  66. ''' </param>
  67. '''
  68. ''' <param name="culture">
  69. ''' A <see cref="CultureInfo"/>. If null is passed, the current culture is assumed.
  70. ''' </param>
  71. '''
  72. ''' <param name="value">
  73. ''' The <see cref="Object"/> to convert.
  74. ''' </param>
  75. '''
  76. ''' <param name="destinationType">
  77. ''' The <see cref="Type"/> to convert the <paramref name="value"/> parameter to.
  78. ''' </param>
  79. '''
  80. ''' <returns>
  81. ''' An <see cref="Object"/> that represents the converted value.
  82. ''' </returns>
  83. <DebuggerStepThrough>
  84. Public Overrides Function ConvertTo(context As ITypeDescriptorContext, culture As CultureInfo, value As Object, destinationType As Type) As Object
  85.  
  86. Dim fi As FieldInfo = Me.EnumType.GetField([Enum].GetName(Me.EnumType, value))
  87. Dim dna As DescriptionAttribute = CType(Attribute.GetCustomAttribute(fi, GetType(DescriptionAttribute)), DescriptionAttribute)
  88. Return If(dna IsNot Nothing, dna.Description, value.ToString())
  89.  
  90. End Function
  91.  
  92. ''' <summary>
  93. ''' Converts the given object to the type of this converter, using the specified context and culture information.
  94. ''' </summary>
  95. '''
  96. ''' <param name="context">
  97. ''' An <see cref="ITypeDescriptorContext"/> that provides a format context.
  98. ''' </param>
  99. '''
  100. ''' <param name="culture">
  101. ''' The <see cref="CultureInfo"/> to use as the current culture.
  102. ''' </param>
  103. '''
  104. ''' <param name="value">
  105. ''' The <see cref="Object"/> to convert.
  106. ''' </param>
  107. '''
  108. ''' <returns>
  109. ''' An <see cref="Object"/> that represents the converted value.
  110. ''' </returns>
  111. <DebuggerStepThrough>
  112. Public Overrides Function ConvertFrom(context As ITypeDescriptorContext, culture As CultureInfo, value As Object) As Object
  113.  
  114. For Each fi As FieldInfo In Me.EnumType.GetFields()
  115. Dim dna As DescriptionAttribute = CType(Attribute.GetCustomAttribute(fi, GetType(DescriptionAttribute)), DescriptionAttribute)
  116. If (dna IsNot Nothing) AndAlso DirectCast(value, String) = dna.Description Then
  117. Return [Enum].Parse(Me.EnumType, fi.Name, ignoreCase:=False)
  118. End If
  119. Next fi
  120.  
  121. Return [Enum].Parse(Me.EnumType, DirectCast(value, String))
  122.  
  123. End Function
  124.  
  125. End Class
  126.  
« Última modificación: 27 Abril 2024, 03:05 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.926



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #593 en: 16 Enero 2025, 15:27 pm »

Clase DllExportAttribute

La clase DllExportAttribute indica que un método puede ser exportado como una función de C, desde una biblioteca de enlace dinámico (DLL) de .NET, lo que hace que el método sea invocable desde código no administrado.

La clase DllExportAttribute está destinada únicamente a replicar y mejorar la clase de atributo DllExportAttribute de plugins como:


Permitiendo que un programador pueda utilizar esta clase de atributo sin necesidad de tener el plugin instalado en sus proyectos de Visual Studio.

Sigue siendo estrictamente necesario utilizar alguno de los proyectos mencionados para habilitar la exportación de funciones .NET.



Capturas de pantalla de la documentación interactiva:













El código fuente:

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 16-January-2025
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Usage Examples "
  15.  
  16. ' VB.NET
  17. ' <DllExport(NameOf(MyStringFunction), CallingConvention.StdCall)>
  18. ' Public Shared Function MyStringFunction() As <MarshalAs(UnmanagedType.BStr)> String
  19. '     Return "Hello World!"
  20. ' End Function
  21.  
  22. ' C#
  23. ' [DllExport(nameof(MyStringFunction), CallingConvention.StdCall)]
  24. ' [return: MarshalAs(UnmanagedType.BStr)]
  25. ' public static string MyStringFunction() {
  26. '     return "Hello World!";
  27. ' }
  28.  
  29. #End Region
  30.  
  31. #Region " Imports "
  32.  
  33. Imports System.Runtime.InteropServices
  34.  
  35. #End Region
  36.  
  37. ' ReSharper disable once CheckNamespace
  38.  
  39. #Region " DllExportAttribute "
  40.  
  41. Namespace DevCase.Runtime.Attributes
  42.  
  43.    ''' <summary>
  44.    ''' The <see cref="DllExportAttribute"/> class indicates that a method can be
  45.    ''' exported as a C function from a .NET dynamic-link library (DLL) file,
  46.    ''' making the method callable from unmanaged code.
  47.    ''' <para></para>
  48.    ''' The <see cref="DllExportAttribute"/> class is solely intended to replicate and improve the
  49.    ''' <b>DllExportAttribute</b> attribute class from plugins like:
  50.    ''' <list type="bullet">
  51.    '''   <item><b>DllExport</b> by 3F
  52.    '''     <para></para>
  53.    '''     <see href="https://github.com/3F/DllExport"/>
  54.    '''   </item>
  55.    '''  
  56.    '''   <item><b>UnmanagedExports</b> by Huajitech
  57.    '''     <para></para>
  58.    '''     <see href="https://github.com/huajitech/UnmanagedExports"/>
  59.    '''   </item>
  60.    '''  
  61.    '''   <item><b>UnmanagedExports.Repack.Upgrade</b> by StevenEngland
  62.    '''     <para></para>
  63.    '''     <see href="https://github.com/stevenengland/UnmanagedExports.Repack.Upgrade"/>
  64.    '''   </item>
  65.    ''' </list>
  66.    ''' Allowing a programmer to use this attribute class without having the plugin installed in their Visual Studio projects.
  67.    ''' <para></para>
  68.    ''' Be aware that it is still necessary to use one of the mentioned projects to enable .NET functions export.
  69.    ''' </summary>
  70.    <AttributeUsage(AttributeTargets.Method, AllowMultiple:=False, Inherited:=False)>
  71.    Public NotInheritable Class DllExportAttribute : Inherits Attribute
  72.  
  73. #Region " Properties "
  74.  
  75.        ''' <summary>
  76.        ''' Gets or sets the calling convention required to call this C-exported function from unmanaged code.
  77.        ''' <para></para>
  78.        ''' Default value is <see cref="System.Runtime.InteropServices.CallingConvention.Cdecl"/>,
  79.        ''' like for other C/C++ programs (Microsoft Specific).
  80.        ''' <para></para>
  81.        ''' Value <see cref="System.Runtime.InteropServices.CallingConvention.StdCall"/> is mostly used with Windows API.
  82.        ''' <para></para>
  83.        ''' </summary>
  84.        Public Property CallingConvention As CallingConvention = CallingConvention.Cdecl
  85.  
  86.        ''' <summary>
  87.        ''' Gets or sets the optional name for this C-exported function.
  88.        ''' </summary>
  89.        ''' <remarks>
  90.        ''' See also:
  91.        ''' <seealso href="https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#FormatC">
  92.        ''' Format of a C decorated name.
  93.        ''' </seealso>
  94.        ''' </remarks>
  95.        Public Property ExportName As String
  96.  
  97. #End Region
  98.  
  99. #Region " Constructors "
  100.  
  101.        ''' <summary>
  102.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  103.        ''' <para></para>
  104.        ''' Use this constructor only if you plan to use <b>DllExport</b> by 3F (<see href="https://github.com/3F/DllExport"/>),
  105.        ''' <para></para>
  106.        ''' otherwise, use <see cref="DllExportAttribute.New(String, CallingConvention)"/>
  107.        ''' to specify the export name and calling convention.
  108.        ''' </summary>
  109.        '''
  110.        ''' <param name="convention">
  111.        ''' The calling convention required to call this C-exported function.
  112.        ''' <para></para>
  113.        ''' Default value is <see cref="System.Runtime.InteropServices.CallingConvention.Cdecl"/>,
  114.        ''' like for other C/C++ programs (Microsoft Specific).
  115.        ''' <para></para>
  116.        ''' Value <see cref="System.Runtime.InteropServices.CallingConvention.StdCall"/> is mostly used with Windows API.
  117.        ''' <para></para>
  118.        ''' </param>
  119.        '''
  120.        ''' <param name="exportName">
  121.        ''' The optional name for this C-exported function.
  122.        ''' See also:
  123.        ''' <seealso href="https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#FormatC">
  124.        ''' Format of a C decorated name.
  125.        ''' </seealso>
  126.        ''' </param>
  127.        Public Sub New(convention As CallingConvention, exportName As String)
  128.  
  129.            Me.CallingConvention = convention
  130.            Me.ExportName = exportName
  131.        End Sub
  132.  
  133.        ''' <summary>
  134.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  135.        ''' <para></para>
  136.        ''' Do not use this constructor if you plan to use <b>DllExport</b> by 3F (<see href="https://github.com/3F/DllExport"/>),
  137.        ''' <para></para>
  138.        ''' in that case use <see cref="DllExportAttribute.New(CallingConvention, String)"/>  
  139.        ''' to specify the export name and calling convention.
  140.        ''' </summary>
  141.        '''
  142.        ''' <param name="exportName">
  143.        ''' The optional name for this C-exported function.
  144.        ''' See also:
  145.        ''' <seealso href="https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#FormatC">
  146.        ''' Format of a C decorated name.
  147.        ''' </seealso>
  148.        ''' </param>
  149.        '''
  150.        ''' <param name="convention">
  151.        ''' The calling convention required to call this C-exported function.
  152.        ''' <para></para>
  153.        ''' Default value is <see cref="System.Runtime.InteropServices.CallingConvention.Cdecl"/>,
  154.        ''' like for other C/C++ programs (Microsoft Specific).
  155.        ''' <para></para>
  156.        ''' Value <see cref="System.Runtime.InteropServices.CallingConvention.StdCall"/> is mostly used with Windows API.
  157.        ''' <para></para>
  158.        ''' </param>
  159.        Public Sub New(exportName As String, convention As CallingConvention)
  160.  
  161.            Me.ExportName = exportName
  162.            Me.CallingConvention = convention
  163.        End Sub
  164.  
  165.        ''' <summary>
  166.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  167.        ''' </summary>
  168.        '''
  169.        ''' <param name="exportName">
  170.        ''' The optional name for this C-exported function.
  171.        ''' See also:
  172.        ''' <seealso href="https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#FormatC">
  173.        ''' Format of a C decorated name.
  174.        ''' </seealso>
  175.        ''' </param>
  176.        Public Sub New(exportName As String)
  177.  
  178.            Me.New(exportName, CallingConvention.Cdecl)
  179.        End Sub
  180.  
  181.        ''' <summary>
  182.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  183.        ''' </summary>
  184.        '''
  185.        ''' <param name="convention">
  186.        ''' The calling convention required to call this C-exported function.
  187.        ''' <para></para>
  188.        ''' Default value is <see cref="System.Runtime.InteropServices.CallingConvention.Cdecl"/>,
  189.        ''' like for other C/C++ programs (Microsoft Specific).
  190.        ''' <para></para>
  191.        ''' Value <see cref="System.Runtime.InteropServices.CallingConvention.StdCall"/> is mostly used with Windows API.
  192.        ''' <para></para>
  193.        ''' </param>
  194.        Public Sub New(convention As CallingConvention)
  195.  
  196.            Me.New(String.Empty, convention)
  197.        End Sub
  198.  
  199.        ''' <summary>
  200.        ''' Initializes a new instance of the <see cref="DllExportAttribute"/> class.
  201.        ''' </summary>
  202.        Public Sub New()
  203.        End Sub
  204.  
  205. #End Region
  206.  
  207.    End Class
  208.  
  209. #End Region
  210.  
  211. End Namespace



Ejemplos de modo de exportación:

VB.NET:
Código
  1. <DllExport(NameOf(MyStringFunction), CallingConvention.StdCall)>
  2. Public Shared Function MyStringFunction() As <MarshalAs(UnmanagedType.BStr)> String
  3.    Return "Hello World!"
  4. End Function

C#:
Código
  1. [DllExport(nameof(MyStringFunction), CallingConvention.StdCall)]
  2. [return: MarshalAs(UnmanagedType.BStr)]
  3. public static string MyStringFunction() {
  4.    return "Hello World!";
  5. }

Ejemplos de modo de importación:

Pascal Script:
Código:
function MyStringFunction(): Cardinal;
  external 'MyStringFunction@files:MyNetAPI.dll stdcall';
« Última modificación: 16 Enero 2025, 16:23 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.926



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #594 en: Ayer a las 11:54 »

Le he dado un lavado de cara moderno a esta impresentable clase del año 2013:
  • Una nueva versión de mi Listview, que tiene muchas cosas interesantes como poder dibujar una barra de progreso en una celda...

He aislado prácticamente toda la lógica de la "barra" de progreso para poder utilizarlo por separado en cualquier tipo de herencia de la clase ListView, en lugar de depender exclusivamente de ese control personalizado ListView que publiqué.

Les presento la clase ListViewProgressBarSubItem que implementa por sí misma (la parte esencial de) el dibujado de la celda y la "barra" de progreso del subitem, proporcionando propiedades de personalización que lo vuelven un elemento flexible y versátil:



💡 Con un poco de mano e ingenio se podría adaptar relativamente fácil dicha clase para dibujar estrellitas (un ranking o puntuación) u otros menesteres varios.

Para ello primero necesitaremos esta simple interfaz:

ISelfDrawableListViewSubItem
Código
  1. ''' <summary>
  2. ''' Provides a contract for a <see cref="ListViewItem.ListViewSubItem"/> that is capable of drawing itself.
  3. ''' </summary>
  4. '''
  5. ''' <remarks>
  6. ''' For this interface to take effect, the owning <see cref="ListView"/> must have its
  7. ''' <see cref="ListView.OwnerDraw"/> property set to <see langword="True"/>, and the
  8. ''' <see cref="ListView.OnDrawSubItem"/> method must be properly overridden to delegate
  9. ''' the drawing logic by calling the <see cref="ISelfDrawableListViewSubItem.Draw(Graphics, Rectangle)"/> method.
  10. ''' <para></para>
  11. ''' See the attached code example for a practical implementation of this functionality.
  12. ''' </remarks>
  13. '''
  14. ''' <example> This is a code example.
  15. ''' <code language="VB">
  16. ''' Public Class CustomListView : Inherits ListView
  17. '''
  18. '''     Public Sub New()
  19. '''
  20. '''         MyBase.New()
  21. '''
  22. '''         Me.DoubleBuffered = True
  23. '''         Me.OwnerDraw = True
  24. '''     End Sub
  25. '''
  26. '''     Protected Overrides Sub OnDrawColumnHeader(e As DrawListViewColumnHeaderEventArgs)
  27. '''
  28. '''         e.DrawDefault = True
  29. '''         MyBase.OnDrawColumnHeader(e)
  30. '''     End Sub
  31. '''
  32. '''     Protected Overrides Sub OnDrawItem(e As DrawListViewItemEventArgs)
  33. '''
  34. '''         e.DrawDefault = False
  35. '''         MyBase.OnDrawItem(e)
  36. '''     End Sub
  37. '''
  38. '''     Protected Overrides Sub OnDrawSubItem(e As DrawListViewSubItemEventArgs)
  39. '''
  40. '''         Dim selfDrawableSubItem As ISelfDrawableListViewSubItem = TryCast(e.SubItem, ISelfDrawableListViewSubItem)
  41. '''         If selfDrawableSubItem IsNot Nothing Then
  42. '''             selfDrawableSubItem.Draw(e.Graphics, e.Bounds)
  43. '''         Else
  44. '''             e.DrawDefault = True
  45. '''         End If
  46. '''
  47. '''         MyBase.OnDrawSubItem(e)
  48. '''     End Sub
  49. '''
  50. ''' End Class
  51. ''' </code>
  52. ''' </example>
  53. Public Interface ISelfDrawableListViewSubItem
  54.  
  55.    ''' <summary>
  56.    ''' Draws the subitem within the specified bounds using the provided <see cref="Graphics"/> surface.
  57.    ''' <para></para>
  58.    ''' This method must be called from the <see cref="ListView.OnDrawSubItem"/> method of the owning <see cref="ListView"/>.
  59.    ''' </summary>
  60.    '''
  61.    ''' <param name="g">
  62.    ''' The <see cref="Graphics"/> surface on which to render the subitem.
  63.    ''' </param>
  64.    '''
  65.    ''' <param name="bounds">
  66.    ''' The <see cref="Rectangle"/> that defines the drawing area for the subitem.
  67.    ''' </param>
  68.    Sub Draw(g As Graphics, bounds As Rectangle)
  69.  
  70. End Interface

Y por último, la clase:

ListViewProgressBarSubItem
Código
  1. ''' <summary>
  2. ''' Represents a custom <see cref="ListViewItem.ListViewSubItem"/> that visually
  3. ''' simulates a progress bar with personalizable text and appearance.
  4. ''' </summary>
  5. '''
  6. ''' <remarks>
  7. ''' For this class to take effect, the owning <see cref="ListView"/> must have its
  8. ''' <see cref="ListView.OwnerDraw"/> property set to <see langword="True"/>, and the
  9. ''' <see cref="ListView.OnDrawSubItem"/> method must be properly overridden to delegate
  10. ''' the drawing logic by calling the <see cref="ListViewProgressBarSubItem.Draw(Graphics, Rectangle)"/> method.
  11. ''' <para></para>
  12. ''' See the attached code example for a practical implementation of this functionality.
  13. ''' </remarks>
  14. '''
  15. ''' <example> This is a code example.
  16. ''' <code language="VB">
  17. ''' Public Class Form1
  18. '''
  19. '''     Private WithEvents CustomListView1 As New CustomListView()
  20. '''
  21. '''     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  22. '''
  23. '''         Dim lv As ListView = Me.CustomListView1
  24. '''         Dim item As New ListViewItem("My item")
  25. '''         Dim subItem As New ListViewProgressBarSubItem(item) With {
  26. '''             .DecimalPlaces = 2,
  27. '''             .TextSuffix = Nothing,
  28. '''             .BorderColor = Color.Empty,
  29. '''             .BackColor = Color.Empty,
  30. '''             .ForeColor = Color.Red,
  31. '''             .FillGradientColorLeft = SystemColors.Highlight,
  32. '''             .FillGradientColorRight = SystemColors.Highlight,
  33. '''             .FillGradientAngle = 0
  34. '''         }
  35. '''
  36. '''         item.SubItems.Add(subItem)
  37. '''         lv.Items.Add(item)
  38. '''     End Sub
  39. '''
  40. ''' End Class
  41. '''
  42. ''' Public Class CustomListView : Inherits ListView
  43. '''
  44. '''     Public Sub New()
  45. '''
  46. '''         MyBase.New()
  47. '''
  48. '''         Me.DoubleBuffered = True
  49. '''         Me.OwnerDraw = True
  50. '''     End Sub
  51. '''
  52. '''     Protected Overrides Sub OnDrawColumnHeader(e As DrawListViewColumnHeaderEventArgs)
  53. '''
  54. '''         e.DrawDefault = True
  55. '''         MyBase.OnDrawColumnHeader(e)
  56. '''     End Sub
  57. '''
  58. '''     Protected Overrides Sub OnDrawItem(e As DrawListViewItemEventArgs)
  59. '''
  60. '''         e.DrawDefault = False
  61. '''         MyBase.OnDrawItem(e)
  62. '''     End Sub
  63. '''
  64. '''     Protected Overrides Sub OnDrawSubItem(e As DrawListViewSubItemEventArgs)
  65. '''
  66. '''         Dim selfDrawableSubItem As ISelfDrawableListViewSubItem = TryCast(e.SubItem, ISelfDrawableListViewSubItem)
  67. '''         If selfDrawableSubItem IsNot Nothing Then
  68. '''             selfDrawableSubItem.Draw(e.Graphics, e.Bounds)
  69. '''         Else
  70. '''             e.DrawDefault = True
  71. '''         End If
  72. '''
  73. '''         MyBase.OnDrawSubItem(e)
  74. '''     End Sub
  75. '''
  76. ''' End Class
  77. ''' </code>
  78. ''' </example>
  79. <Serializable>
  80. <TypeConverter(GetType(ExpandableObjectConverter))>
  81. <ToolboxItem(False)>
  82. <DesignTimeVisible(False)>
  83. <DefaultProperty("Text")>
  84. Public Class ListViewProgressBarSubItem : Inherits ListViewItem.ListViewSubItem : Implements ISelfDrawableListViewSubItem
  85.  
  86. #Region " Fields "
  87.  
  88.    ''' <summary>
  89.    ''' The default font of the text displayed by the subitem.
  90.    ''' </summary>
  91.    <NonSerialized>
  92.    Protected defaultFont As Font = MyBase.Font
  93.  
  94.    ''' <summary>
  95.    ''' The default background color of the subitem's text.
  96.    ''' </summary>
  97.    <NonSerialized>
  98.    Protected defaultBackColor As Color = MyBase.BackColor
  99.  
  100.    ''' <summary>
  101.    ''' The default foreground color of the subitem's text.
  102.    ''' </summary>
  103.    <NonSerialized>
  104.    Protected defaultForeColor As Color = MyBase.ForeColor
  105.  
  106.    ''' <summary>
  107.    ''' The default angle to draw the linear gradient specified by  
  108.    ''' <see cref="ListViewProgressBarSubItem.FillGradientColorLeft"/>
  109.    ''' and <see cref="ListViewProgressBarSubItem.FillGradientColorRight"/> colors.
  110.    ''' </summary>
  111.    <NonSerialized>
  112.    Protected defaultFillGradientAngle As Single = 0
  113.  
  114.    ''' <summary>
  115.    ''' The default starting linear gradient color to fill the progress area.
  116.    ''' </summary>
  117.    <NonSerialized>
  118.    Protected defaultFillGradientColorLeft As Color = SystemColors.HighlightText
  119.  
  120.    ''' <summary>
  121.    ''' The default ending linear gradient color to fill the progress area.
  122.    ''' </summary>
  123.    <NonSerialized>
  124.    Protected defaultFillGradientColorRight As Color = SystemColors.Highlight
  125.  
  126.    ''' <summary>
  127.    ''' The default color of the progress bar border.
  128.    ''' </summary>
  129.    <NonSerialized>
  130.    Protected defaultBorderColor As Color = SystemColors.InactiveBorder
  131.  
  132.    ''' <summary>
  133.    ''' The default <see cref="System.Windows.Forms.TextFormatFlags"/> that determine
  134.    ''' how the subitem text is rendered and aligned.
  135.    ''' </summary>
  136.    <NonSerialized>
  137.    Protected defaultTextFormatFlags As TextFormatFlags =
  138.        TextFormatFlags.HorizontalCenter Or
  139.        TextFormatFlags.VerticalCenter Or
  140.        TextFormatFlags.EndEllipsis Or
  141.        TextFormatFlags.SingleLine
  142.  
  143. #End Region
  144.  
  145. #Region " Properties "
  146.  
  147.    ''' <summary>
  148.    ''' Gets or sets the current progress percentage value to display in the progress bar.
  149.    ''' <para></para>
  150.    ''' The value should be between 0 to 100.
  151.    ''' </summary>
  152.    Public Property ProgressPercentage As Double
  153.        Get
  154.            Return Me.progressPercentage_
  155.        End Get
  156.        <DebuggerStepThrough>
  157.        Set(value As Double)
  158.            Me.SetFieldValue(Me.progressPercentage_, value)
  159.        End Set
  160.    End Property
  161.    ''' <summary>
  162.    ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> property )
  163.    ''' <para></para>
  164.    ''' The current progress percentage value to display in the progress bar.
  165.    ''' </summary>
  166.    Private progressPercentage_ As Double
  167.  
  168.    ''' <summary>
  169.    ''' Gets or sets the number of decimal places displayed for the <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> value.
  170.    ''' <para></para>
  171.    ''' Default value is zero.
  172.    ''' </summary>
  173.    Public Property DecimalPlaces As Short
  174.        Get
  175.            Return Me.decimalPlaces_
  176.        End Get
  177.        <DebuggerStepThrough>
  178.        Set(value As Short)
  179.            Me.SetFieldValue(Me.decimalPlaces_, value)
  180.        End Set
  181.    End Property
  182.    ''' <summary>
  183.    ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.DecimalPlaces"/> property )
  184.    ''' <para></para>
  185.    ''' The number of decimal places displayed for the <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> value.
  186.    ''' </summary>
  187.    Private decimalPlaces_ As Short
  188.  
  189.    ''' <summary>
  190.    ''' Gets or sets the additional text displayed next to the <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> value.
  191.    ''' </summary>
  192.    Public Property TextSuffix As String
  193.        Get
  194.            Return Me.textSuffix_
  195.        End Get
  196.        <DebuggerStepThrough>
  197.        Set(value As String)
  198.            Me.SetFieldValue(Me.textSuffix_, value)
  199.        End Set
  200.    End Property
  201.    ''' <summary>
  202.    ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.TextSuffix"/> property )
  203.    ''' <para></para>
  204.    ''' The additional text displayed next to the <see cref="ListViewProgressBarSubItem.ProgressPercentage"/> value.
  205.    ''' </summary>
  206.    Private textSuffix_ As String
  207.  
  208.    ''' <summary>
  209.    ''' Gets or sets the <see cref="System.Windows.Forms.TextFormatFlags"/> that determine
  210.    ''' how the subitem text is rendered and aligned.
  211.    ''' <para></para>
  212.    ''' Default value is:
  213.    ''' <see cref="System.Windows.Forms.TextFormatFlags.HorizontalCenter"/>,
  214.    ''' <see cref="System.Windows.Forms.TextFormatFlags.VerticalCenter"/>,
  215.    ''' <see cref="System.Windows.Forms.TextFormatFlags.EndEllipsis"/> and
  216.    ''' <see cref="System.Windows.Forms.TextFormatFlags.SingleLine"/>
  217.    ''' </summary>
  218.    Public Property TextFormatFlags As TextFormatFlags
  219.        Get
  220.            Return Me.textFormatFlags_
  221.        End Get
  222.        <DebuggerStepThrough>
  223.        Set(value As TextFormatFlags)
  224.            Me.SetFieldValue(Me.textFormatFlags_, value)
  225.        End Set
  226.    End Property
  227.    ''' <summary>
  228.    ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.TextFormatFlags"/> property )
  229.    ''' <para></para>
  230.    ''' The <see cref="System.Windows.Forms.TextFormatFlags"/> that determine how the subitem text is rendered.
  231.    ''' </summary>
  232.    Private textFormatFlags_ As TextFormatFlags
  233.  
  234.    ''' <summary>
  235.    ''' Gets or sets the starting linear gradient color to fill the progress area.
  236.    ''' <para></para>
  237.    ''' Default value is <see cref="SystemColors.Control"/>.
  238.    ''' </summary>
  239.    Public Property FillGradientColorLeft As Color
  240.        Get
  241.            Return Me.fillGradientColorLeft_
  242.        End Get
  243.        <DebuggerStepThrough>
  244.        Set(value As Color)
  245.            Me.SetFieldValue(Me.fillGradientColorLeft_, value)
  246.        End Set
  247.    End Property
  248.    ''' <summary>
  249.    ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.FillGradientColorLeft"/> property )
  250.    ''' <para></para>
  251.    ''' The starting linear gradient color to fill the progress area.
  252.    ''' </summary>
  253.    Private fillGradientColorLeft_ As Color
  254.  
  255.    ''' <summary>
  256.    ''' Gets or sets the ending linear gradient color to fill the progress area.
  257.    ''' <para></para>
  258.    ''' Default value is <see cref="Color.LightGreen"/>.
  259.    ''' </summary>
  260.    Public Property FillGradientColorRight As Color
  261.        Get
  262.            Return Me.fillGradientColorRight_
  263.        End Get
  264.        <DebuggerStepThrough>
  265.        Set(value As Color)
  266.            Me.SetFieldValue(Me.fillGradientColorRight_, value)
  267.        End Set
  268.    End Property
  269.    ''' <summary>
  270.    ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.FillGradientColorRight"/> property )
  271.    ''' <para></para>
  272.    ''' The ending linear gradient color to fill the progress area.
  273.    ''' </summary>
  274.    Private fillGradientColorRight_ As Color
  275.  
  276.    ''' <summary>
  277.    ''' Gets or sets the angle to draw the linear gradient specified by  
  278.    ''' <see cref="ListViewProgressBarSubItem.FillGradientColorLeft"/>
  279.    ''' and <see cref="ListViewProgressBarSubItem.FillGradientColorRight"/> colors.
  280.    ''' <para></para>
  281.    ''' Default value is zero.
  282.    ''' </summary>
  283.    Public Property FillGradientAngle As Single
  284.        Get
  285.            Return Me.fillGradientAngle_
  286.        End Get
  287.        <DebuggerStepThrough>
  288.        Set(value As Single)
  289.            Me.SetFieldValue(Me.fillGradientAngle_, value)
  290.        End Set
  291.    End Property
  292.    ''' <summary>
  293.    ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.FillGradientAngle"/> property )
  294.    ''' <para></para>
  295.    ''' The angle to draw the linear gradient specified by  
  296.    ''' <see cref="ListViewProgressBarSubItem.FillGradientColorLeft"/>
  297.    ''' and <see cref="ListViewProgressBarSubItem.FillGradientColorRight"/> colors.
  298.    ''' </summary>
  299.    Private fillGradientAngle_ As Single
  300.  
  301.    ''' <summary>
  302.    ''' Gets or sets the color of the progress bar border.
  303.    ''' <para></para>
  304.    ''' Default value is <see cref="SystemColors.ActiveBorder"/>.
  305.    ''' </summary>
  306.    Public Property BorderColor As Color
  307.        Get
  308.            Return Me.borderColor_
  309.        End Get
  310.        <DebuggerStepThrough>
  311.        Set(value As Color)
  312.            Me.SetFieldValue(Me.borderColor_, value)
  313.        End Set
  314.    End Property
  315.    ''' <summary>
  316.    ''' ( Backing Field of <see cref="ListViewProgressBarSubItem.BorderColor"/> property )
  317.    ''' <para></para>
  318.    ''' The color of the progress bar border.
  319.    ''' </summary>
  320.    Private borderColor_ As Color
  321.  
  322.    ''' <summary>
  323.    ''' Gets or sets the background color of the subitem cell.
  324.    ''' </summary>
  325.    Public Shadows Property BackColor As Color
  326.        Get
  327.            Return MyBase.BackColor
  328.        End Get
  329.        <DebuggerStepThrough>
  330.        Set(value As Color)
  331.            Me.SetFieldValue(MyBase.BackColor, value)
  332.        End Set
  333.    End Property
  334.  
  335.    ''' <summary>
  336.    ''' Gets or sets the foreground color of the subitem's text.
  337.    ''' </summary>
  338.    Public Shadows Property ForeColor As Color
  339.        Get
  340.            Return MyBase.ForeColor
  341.        End Get
  342.        <DebuggerStepThrough>
  343.        Set(value As Color)
  344.            Me.SetFieldValue(MyBase.ForeColor, value)
  345.        End Set
  346.    End Property
  347.  
  348.    ''' <summary>
  349.    ''' Gets or sets the font of the text displayed by the subitem.
  350.    ''' </summary>
  351.    Public Shadows Property Font As Font
  352.        Get
  353.            Return MyBase.Font
  354.        End Get
  355.        Set(value As Font)
  356.            Me.SetFieldValue(MyBase.Font, value)
  357.        End Set
  358.    End Property
  359.  
  360.    ''' <summary>
  361.    ''' Gets the text of the subitem.
  362.    ''' </summary>
  363.    Public Shadows ReadOnly Property Text As String
  364.        Get
  365.            Return Me.progressPercentage_.ToString("N" & Me.decimalPlaces_) & "%" &
  366.                   If(String.IsNullOrEmpty(Me.textSuffix_), Nothing, " " & Me.textSuffix_)
  367.        End Get
  368.    End Property
  369.  
  370. #End Region
  371.  
  372. #Region " Constructors "
  373.  
  374.    ''' <summary>
  375.    ''' Initializes a new instance of the <see cref="ListViewProgressBarSubItem"/> class
  376.    ''' associated with the given <see cref="ListViewItem"/>.
  377.    ''' </summary>
  378.    '''
  379.    ''' <param name="owner">
  380.    ''' A <see cref="ListViewItem"/> that represents the item that owns this <see cref="ListViewProgressBarSubItem"/>.
  381.    ''' </param>
  382.    <DebuggerStepThrough>
  383.    Public Sub New(owner As ListViewItem)
  384.  
  385.        MyBase.New(owner, String.Empty)
  386.        Me.ResetStyle()
  387.    End Sub
  388.  
  389.    ''' <summary>
  390.    ''' Initializes a new instance of the <see cref="ListViewProgressBarSubItem"/> class.
  391.    ''' </summary>
  392.    <DebuggerStepThrough>
  393.    Public Sub New()
  394.  
  395.        Me.ResetStyle()
  396.    End Sub
  397.  
  398. #End Region
  399.  
  400. #Region " Public Methods "
  401.  
  402.    ''' <summary>
  403.    ''' Resets the styles applied to the subitem to the default font and colors.
  404.    ''' </summary>
  405.    <DebuggerStepThrough>
  406.    Public Shadows Sub ResetStyle()
  407.  
  408.        MyBase.Font = Me.defaultFont
  409.        MyBase.BackColor = Me.defaultBackColor
  410.        MyBase.ForeColor = Me.defaultForeColor
  411.  
  412.        Me.textFormatFlags_ = Me.defaulttextFormatFlags
  413.        Me.fillGradientColorLeft_ = Me.defaultFillGradientColorLeft
  414.        Me.fillGradientColorRight_ = Me.defaultFillGradientColorRight
  415.        Me.fillGradientAngle_ = Me.defaultFillGradientAngle
  416.        Me.borderColor_ = Me.defaultBorderColor
  417.  
  418.        Me.RefreshSubItem()
  419.    End Sub
  420.  
  421. #End Region
  422.  
  423. #Region " Private Methods "
  424.  
  425.    ''' <summary>
  426.    ''' Sets the value of the specified field using <see cref="EqualityComparer(Of T)"/> to check value equality.
  427.    ''' <para></para>
  428.    ''' If the new value is different from the current one,
  429.    ''' it then calls <see cref="ListViewProgressBarSubItem.RefreshSubItem"/> method.
  430.    ''' </summary>
  431.    '''
  432.    ''' <typeparam name="T">
  433.    ''' The type of the property value.
  434.    ''' </typeparam>
  435.    '''
  436.    ''' <param name="refField">
  437.    ''' A reference to the backing field of the property.
  438.    ''' </param>
  439.    '''
  440.    ''' <param name="newValue">
  441.    ''' The new value to set.
  442.    ''' </param>
  443.    <DebuggerStepThrough>
  444.    Private Sub SetFieldValue(Of T)(ByRef refField As T, newValue As T)
  445.  
  446.        If Not EqualityComparer(Of T).Default.Equals(refField, newValue) Then
  447.            refField = newValue
  448.            Me.RefreshSubItem()
  449.        End If
  450.    End Sub
  451.  
  452.    ''' <summary>
  453.    ''' Refreshes the visual representation of this <see cref="ListViewProgressBarSubItem"/> subitem
  454.    ''' in the owner <see cref="ListView"/> by invalidating its bounding rectangle.
  455.    ''' </summary>
  456.    '''
  457.    ''' <remarks>
  458.    ''' This method uses reflection to access the non-public "owner" field of the base
  459.    ''' <see cref="ListViewItem.ListViewSubItem"/> class in order to identify the parent item and column index.
  460.    ''' It then triggers a redraw of the specific subitem area within the parent ListView.
  461.    ''' </remarks>
  462.    <DebuggerStepThrough>
  463.    Private Sub RefreshSubItem()
  464.  
  465.        Dim fieldInfo As FieldInfo =
  466.            GetType(ListViewItem.ListViewSubItem).GetField("owner", BindingFlags.NonPublic Or BindingFlags.Instance)
  467.  
  468.        If fieldInfo IsNot Nothing Then
  469.            Dim ownerObj As Object = fieldInfo.GetValue(Me)
  470.  
  471.            If ownerObj IsNot Nothing Then
  472.                Dim lvi As ListViewItem = DirectCast(ownerObj, ListViewItem)
  473.                Dim colIndex As Integer = lvi.SubItems.IndexOf(Me)
  474.  
  475.                If colIndex >= 0 AndAlso lvi.ListView IsNot Nothing Then
  476.                    Dim subItemBounds As Rectangle = lvi.SubItems(colIndex).Bounds
  477.                    lvi.ListView.Invalidate(subItemBounds, invalidateChildren:=False)
  478.                End If
  479.            End If
  480.        End If
  481.    End Sub
  482.  
  483. #End Region
  484.  
  485. #Region " ISelfDrawableListViewSubItem Implementation "
  486.  
  487.    ''' <summary>
  488.    ''' Draws the subitem within the specified bounds using the provided <see cref="Graphics"/> surface.
  489.    ''' <para></para>
  490.    ''' This method must be called from the <see cref="ListView.OnDrawSubItem"/> method of the owning <see cref="ListView"/>.
  491.    ''' </summary>
  492.    '''
  493.    ''' <param name="g">
  494.    ''' The <see cref="Graphics"/> surface on which to render the subitem.
  495.    ''' </param>
  496.    '''
  497.    ''' <param name="bounds">
  498.    ''' The <see cref="Rectangle"/> that defines the drawing area for the subitem.
  499.    ''' </param>
  500.    <DebuggerStepThrough>
  501.    Protected Sub Draw(g As Graphics, bounds As Rectangle) Implements ISelfDrawableListViewSubItem.Draw
  502.  
  503.        ' Draw subitem background (progress bar background).
  504.        If Me.BackColor <> Color.Empty AndAlso Me.BackColor <> Color.Transparent Then
  505.  
  506.            Using backBrush As New SolidBrush(Me.BackColor)
  507.                g.FillRectangle(backBrush, bounds)
  508.            End Using
  509.        End If
  510.  
  511.        ' Draw linear gradient to fill the current progress of the progress bar.
  512.        If (Me.fillGradientColorLeft_ <> Color.Empty AndAlso Me.fillGradientColorLeft_ <> Color.Transparent) OrElse
  513.           (Me.fillGradientColorRight_ <> Color.Empty AndAlso Me.fillGradientColorRight_ <> Color.Transparent) Then
  514.  
  515.            Using brGradient As New Drawing2D.LinearGradientBrush(
  516.                New Rectangle(bounds.X, bounds.Y, bounds.Width, bounds.Height),
  517.                Me.fillGradientColorLeft_, Me.fillGradientColorRight_,
  518.                Me.fillGradientAngle_, isAngleScaleable:=True)
  519.  
  520.                Dim progressWidth As Integer = CInt((Me.progressPercentage_ / 100) * (bounds.Width - 2))
  521.                g.FillRectangle(brGradient, bounds.X + 1, bounds.Y + 2, progressWidth, bounds.Height - 3)
  522.            End Using
  523.        End If
  524.  
  525.        ' Draw subitem text.
  526.        Dim text As String = Me.Text
  527.        If Not String.IsNullOrEmpty(text) Then
  528.  
  529.            TextRenderer.DrawText(g, text, Me.Font, bounds, Me.ForeColor, Me.TextFormatFlags)
  530.        End If
  531.  
  532.        ' Draw border around the progress bar.
  533.        If Me.borderColor_ <> Color.Empty AndAlso Me.borderColor_ <> Color.Transparent Then
  534.            Using borderPen As New Pen(Me.borderColor_)
  535.                g.DrawRectangle(borderPen, bounds.X, bounds.Y + 1, bounds.Width - 2, bounds.Height - 2)
  536.            End Using
  537.        End If
  538.  
  539.    End Sub
  540.  
  541. #End Region
  542.  
  543. End Class

Ejemplo de uso:
Código
  1. Public Class Form1
  2.  
  3.     Private WithEvents CustomListView1 As New CustomListView()
  4.  
  5.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  6.  
  7.         Dim lv As ListView = Me.CustomListView1
  8.         Dim item As New ListViewItem("My item")
  9.         Dim subItem As New ListViewProgressBarSubItem(item) With {
  10.             .DecimalPlaces = 2,
  11.             .TextSuffix = Nothing,
  12.             .BorderColor = Color.Empty,
  13.             .BackColor = Color.Empty,
  14.             .ForeColor = Color.Red,
  15.             .FillGradientColorLeft = SystemColors.Highlight,
  16.             .FillGradientColorRight = SystemColors.Highlight,
  17.             .FillGradientAngle = 0
  18.         }
  19.  
  20.         item.SubItems.Add(subItem)
  21.         lv.Items.Add(item)
  22.     End Sub
  23.  
  24. End Class
  25.  
  26. Public Class CustomListView : Inherits ListView
  27.  
  28.     Public Sub New()
  29.  
  30.         MyBase.New()
  31.  
  32.         Me.DoubleBuffered = True
  33.         Me.OwnerDraw = True
  34.     End Sub
  35.  
  36.     Protected Overrides Sub OnDrawColumnHeader(e As DrawListViewColumnHeaderEventArgs)
  37.  
  38.         e.DrawDefault = True
  39.         MyBase.OnDrawColumnHeader(e)
  40.     End Sub
  41.  
  42.     Protected Overrides Sub OnDrawItem(e As DrawListViewItemEventArgs)
  43.  
  44.         e.DrawDefault = False
  45.         MyBase.OnDrawItem(e)
  46.     End Sub
  47.  
  48.     Protected Overrides Sub OnDrawSubItem(e As DrawListViewSubItemEventArgs)
  49.  
  50.         Dim selfDrawableSubItem As ISelfDrawableListViewSubItem = TryCast(e.SubItem, ISelfDrawableListViewSubItem)
  51.         If selfDrawableSubItem IsNot Nothing Then
  52.             selfDrawableSubItem.Draw(e.Graphics, e.Bounds)
  53.         Else
  54.             e.DrawDefault = True
  55.         End If
  56.  
  57.         MyBase.OnDrawSubItem(e)
  58.     End Sub
  59.  
  60. End Class
« Última modificación: Ayer a las 14:25 por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.926



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #595 en: Hoy a las 01:15 »

Cómo iniciar el programa warp-cli.exe de la VPN de Cloudflare Warp pasándole un comando

Un simple método para ejecutar el programa warp-cli.exe de la VPN de Cloudflare Warp pasándole un comando (ej. "connect", "disconnect", etc):

Código
  1. ''' <summary>
  2. ''' Sends a custom command to the Cloudflare Warp CLI executable (<c>warp-cli.exe</c>)
  3. ''' and captures both standard output and error output.
  4. ''' </summary>
  5. '''
  6. ''' <param name="command">
  7. ''' The command-line argument to be passed to warp-cli executable.
  8. ''' For example: <c>connect</c>, <c>disconnect</c>, <c>status</c>, etc.
  9. ''' </param>
  10. '''
  11. ''' <param name="refOutput">
  12. ''' Returns the standard output returned by the warp-cli process.
  13. ''' </param>
  14. '''
  15. ''' <param name="refErrorOutput">
  16. ''' Returns the standard error output returned by the warp-cli process.
  17. ''' </param>
  18. '''
  19. ''' <param name="warpCliFilePath">
  20. ''' Optional path to the warp-cli executable. If <c>Nothing</c> is specified, the method defaults to:
  21. ''' <c>%ProgramFiles%\Cloudflare\Cloudflare Warp\warp-cli.exe</c>.
  22. ''' </param>
  23. '''
  24. ''' <returns>
  25. ''' The exit code returned by the warp-cli process. A value of 0 typically indicates success.
  26. ''' </returns>
  27. '''
  28. ''' <exception cref="System.IO.FileNotFoundException">
  29. ''' Thrown if the specified or default warp-cli executable file is not found on the system.
  30. ''' </exception>
  31. '''
  32. ''' <exception cref="System.TimeoutException">
  33. ''' Thrown if the warp-cli process takes longer than 60 seconds to complete.
  34. ''' </exception>
  35. '''
  36. ''' <exception cref="System.Exception">
  37. ''' Thrown if any other unexpected error occurs while attempting to execute the warp-cli process.
  38. ''' The original exception is wrapped as the inner exception.
  39. ''' </exception>
  40. <DebuggerStepThrough>
  41. Public Shared Function CloudflareWarpCliSendCommand(command As String,
  42.                                                    ByRef refOutput As String,
  43.                                                    ByRef refErrorOutput As String,
  44.                                                    Optional warpCliFilePath As String = Nothing) As Integer
  45.  
  46.    ' Prevents concurrent execution of the method from multiple threads within the same process.
  47.    ' This static lock object ensures that only one thread can execute the critical section at a time,
  48.    ' avoiding race conditions or conflicts when invoking the Warp CLI.
  49.    Static WarpCliLock As New Object()
  50.  
  51.    Static spaceChar As Char = " "c
  52.  
  53.    SyncLock WarpCliLock
  54.        If String.IsNullOrEmpty(warpCliFilePath) Then
  55.            warpCliFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
  56.                                           "Cloudflare\Cloudflare Warp\warp-cli.exe")
  57.        End If
  58.  
  59.        Try
  60.            If Not System.IO.File.Exists(warpCliFilePath) Then
  61.                Throw New System.IO.FileNotFoundException("The Warp CLI executable was not found.", warpCliFilePath)
  62.            End If
  63.  
  64.            Using pr As New Process()
  65.                pr.StartInfo.FileName = warpCliFilePath
  66.                pr.StartInfo.Arguments = command
  67.                pr.StartInfo.UseShellExecute = False
  68.                pr.StartInfo.CreateNoWindow = True
  69.                pr.StartInfo.RedirectStandardOutput = True
  70.                pr.StartInfo.RedirectStandardError = True
  71.  
  72.                pr.Start()
  73.                If Not pr.WaitForExit(60000) Then ' Waits a maximum of 60 seconds
  74.                    pr.Kill()
  75.                    Throw New TimeoutException("warp-cli process has timed out.")
  76.                End If
  77.  
  78.                refOutput = pr.StandardOutput.ReadToEnd().Trim(Environment.NewLine.ToCharArray().Concat({spaceChar}).ToArray())
  79.                refErrorOutput = pr.StandardError.ReadToEnd().Trim(Environment.NewLine.ToCharArray().Concat({spaceChar}).ToArray())
  80.  
  81.                Return pr.ExitCode
  82.            End Using
  83.  
  84.        Catch ex As Exception
  85.            Throw New Exception($"Failed to execute warp-cli process. See inner exception for details.", ex)
  86.        End Try
  87.    End SyncLock
  88. End Function

Casos de uso reales: para conectar a la red de Cloudflare WARP en cualquier proyecto donde hagamos solicitudes http, por ejemplo en un web-crawler, a sitios web con riesgo de que puedan acabar bloqueando nuestra IP.



Tres métodos de extensión para dibujar texto sobre una imagen, o dibujar encima otra imagen (con capacidad opcional de usar transparencia) o un valor numérico, con una escala proporcional a la imagen y en una posición alineada a cualquiera de las esquinas o zonas centrales de la imagen (centro absoluto, parte superior central o parte inferior central) de la imagen.

Demostración de resultado de la extensión que dibuja un valor numérico (de forma alineada a la esquina inferior derecha de la imagen):



Código
  1. ''' <summary>
  2. ''' Draws an overlay image onto the specified <see cref="Image"/> at a given position and scale factor.
  3. ''' </summary>
  4. '''
  5. ''' <param name="refImg">
  6. ''' The source <see cref="Image"/> to modify. The overlay image will be drawn directly on this image.
  7. ''' </param>
  8. '''
  9. ''' <param name="overlayImg">
  10. ''' The overlay image to draw on the source <paramref name="refImg"/>.
  11. ''' </param>
  12. '''
  13. ''' <param name="scale">
  14. ''' The relative image scale factor to determine overlay image size. Lower values increase the size of the overlay image.
  15. ''' </param>
  16. '''
  17. ''' <param name="position">
  18. ''' The position/alignment where the overlay image should be drawn (e.g., bottom-right).
  19. ''' </param>
  20. '''
  21. ''' <param name="margin">
  22. ''' The margin (in pixels) from the edge of the image to position the overlay image.
  23. ''' <para></para>
  24. ''' This value has different meaning depending on <paramref name="position"/> parameter:
  25. ''' <para></para>
  26. ''' <list type="bullet">
  27. '''   <item>
  28. '''     <term>
  29. '''       <see cref="ContentAlignment.TopLeft"/>, <see cref="ContentAlignment.TopRight"/>,
  30. '''       <para></para>
  31. '''       <see cref="ContentAlignment.BottomLeft"/> and <see cref="ContentAlignment.BottomRight"/>
  32. '''     </term>
  33. '''     <description><para></para><paramref name="margin"/> specifies the diagonal offset.</description>
  34. '''   </item>
  35. '''   <item>
  36. '''     <term>
  37. '''       <see cref="ContentAlignment.MiddleLeft"/> and <see cref="ContentAlignment.MiddleRight"/>
  38. '''     </term>
  39. '''     <description><para></para><paramref name="margin"/> specifies the horizontal offset.</description>
  40. '''   </item>
  41. '''   <item>
  42. '''     <term>
  43. '''       <see cref="ContentAlignment.TopCenter"/> and <see cref="ContentAlignment.BottomCenter"/>
  44. '''     </term>
  45. '''     <description><para></para><paramref name="margin"/> specifies the vertical offset.</description>
  46. '''   </item>
  47. '''   <item>
  48. '''     <term>
  49. '''       <see cref="ContentAlignment.MiddleCenter"/>
  50. '''     </term>
  51. '''     <description><para></para><paramref name="margin"/> is ignored.</description>
  52. '''   </item>
  53. ''' </list>
  54. ''' </param>
  55. '''
  56. ''' <param name="transparentColor">
  57. ''' Optional. A <see cref="Color"/> to use as transparency to draw the overlay image.
  58. ''' </param>
  59. <DebuggerStepThrough>
  60. <Extension>
  61. <EditorBrowsable(EditorBrowsableState.Always)>
  62. Public Sub DrawImageScaled(ByRef refImg As Image, overlayImg As Image,
  63.                       scale As Single, position As ContentAlignment, margin As Single,
  64.                       Optional transparentColor As Color? = Nothing)
  65.  
  66.    If refImg Is Nothing Then
  67.        Throw New ArgumentNullException(NameOf(refImg))
  68.    End If
  69.  
  70.    If overlayImg Is Nothing Then
  71.        Throw New ArgumentNullException(NameOf(overlayImg))
  72.    End If
  73.  
  74.    If margin < 0 Then
  75.        Throw New ArgumentOutOfRangeException(NameOf(margin), margin, "Margin must be greater than or equal to 0.")
  76.    End If
  77.  
  78.    If scale < 1 Then
  79.        Throw New ArgumentOutOfRangeException(NameOf(scale), scale, "Font scale must be greater than or equal to 1.")
  80.    End If
  81.  
  82.    Using g As Graphics = Graphics.FromImage(refImg)
  83.        g.SmoothingMode = SmoothingMode.AntiAlias
  84.        g.InterpolationMode = InterpolationMode.HighQualityBicubic
  85.        g.PixelOffsetMode = PixelOffsetMode.HighQuality
  86.        g.CompositingQuality = CompositingQuality.HighQuality
  87.  
  88.        Dim targetSize As Single = Math.Max(refImg.Width, refImg.Height) / scale
  89.        Dim aspectRatio As Single = CSng(overlayImg.Width / overlayImg.Height)
  90.  
  91.        Dim drawWidth As Single
  92.        Dim drawHeight As Single
  93.  
  94.        If overlayImg.Width >= overlayImg.Height Then
  95.            drawWidth = targetSize
  96.            drawHeight = targetSize / aspectRatio
  97.        Else
  98.            drawHeight = targetSize
  99.            drawWidth = targetSize * aspectRatio
  100.        End If
  101.  
  102.        Dim posX As Single = 0
  103.        Dim posY As Single = 0
  104.  
  105.        Select Case position
  106.            Case ContentAlignment.TopLeft
  107.                posX = margin
  108.                posY = margin
  109.  
  110.            Case ContentAlignment.TopCenter
  111.                posX = (refImg.Width - drawWidth) / 2
  112.                posY = margin
  113.  
  114.            Case ContentAlignment.TopRight
  115.                posX = refImg.Width - drawWidth - margin
  116.                posY = margin
  117.  
  118.            Case ContentAlignment.MiddleLeft
  119.                posX = margin
  120.                posY = (refImg.Height - drawHeight) / 2
  121.  
  122.            Case ContentAlignment.MiddleCenter
  123.                posX = (refImg.Width - drawWidth) / 2
  124.                posY = (refImg.Height - drawHeight) / 2
  125.  
  126.            Case ContentAlignment.MiddleRight
  127.                posX = refImg.Width - drawWidth - margin
  128.                posY = (refImg.Height - drawHeight) / 2
  129.  
  130.            Case ContentAlignment.BottomLeft
  131.                posX = margin
  132.                posY = refImg.Height - drawHeight - margin
  133.  
  134.            Case ContentAlignment.BottomCenter
  135.                posX = (refImg.Width - drawWidth) / 2
  136.                posY = refImg.Height - drawHeight - margin
  137.  
  138.            Case ContentAlignment.BottomRight
  139.                posX = refImg.Width - drawWidth - margin
  140.                posY = refImg.Height - drawHeight - margin
  141.  
  142.            Case Else
  143.                Throw New InvalidEnumArgumentException(NameOf(position), position, GetType(ContentAlignment))
  144.        End Select
  145.  
  146.        If transparentColor.HasValue Then
  147.            Using attr As New Imaging.ImageAttributes()
  148.                attr.SetColorKey(transparentColor.Value, transparentColor.Value)
  149.  
  150.                Dim destRect As New Rectangle(CInt(posX), CInt(posY), CInt(drawWidth), CInt(drawHeight))
  151.                g.DrawImage(overlayImg, destRect, 0, 0, overlayImg.Width, overlayImg.Height, GraphicsUnit.Pixel, attr)
  152.            End Using
  153.        Else
  154.            g.DrawImage(overlayImg, posX, posY, drawWidth, drawHeight)
  155.        End If
  156.    End Using
  157. End Sub
  158.  
  159. ''' <summary>
  160. ''' Draws text onto the specified <see cref="Image"/> at a given position and scale factor.
  161. ''' </summary>
  162. '''
  163. ''' <param name="refImg">
  164. ''' The <see cref="Image"/> to modify. The text will be drawn directly on this image.
  165. ''' </param>
  166. '''
  167. ''' <param name="text">
  168. ''' The text to draw on the image.
  169. ''' </param>
  170. '''
  171. ''' <param name="scale">
  172. ''' The relative image scale factor to determine font size. Lower values increase the size of the text.
  173. ''' <para></para>
  174. ''' Suggested value is from 10 to 20.
  175. ''' </param>
  176. '''
  177. ''' <param name="position">
  178. ''' The position/alignment where the text should be drawn (e.g., bottom-right).
  179. ''' </param>
  180. '''
  181. ''' <param name="margin">
  182. ''' The margin (in pixels) from the edge of the image to position the text.
  183. ''' <para></para>
  184. ''' This value has different meaning depending on <paramref name="position"/> parameter:
  185. ''' <para></para>
  186. ''' <list type="bullet">
  187. '''   <item>
  188. '''     <term>
  189. '''       <see cref="ContentAlignment.TopLeft"/>, <see cref="ContentAlignment.TopRight"/>,
  190. '''       <para></para>
  191. '''       <see cref="ContentAlignment.BottomLeft"/> and <see cref="ContentAlignment.BottomRight"/>
  192. '''     </term>
  193. '''     <description><para></para><paramref name="margin"/> specifies the diagonal offset.</description>
  194. '''   </item>
  195. '''   <item>
  196. '''     <term>
  197. '''       <see cref="ContentAlignment.MiddleLeft"/> and <see cref="ContentAlignment.MiddleRight"/>
  198. '''     </term>
  199. '''     <description><para></para><paramref name="margin"/> specifies the horizontal offset.</description>
  200. '''   </item>
  201. '''   <item>
  202. '''     <term>
  203. '''       <see cref="ContentAlignment.TopCenter"/> and <see cref="ContentAlignment.BottomCenter"/>
  204. '''     </term>
  205. '''     <description><para></para><paramref name="margin"/> specifies the vertical offset.</description>
  206. '''   </item>
  207. '''   <item>
  208. '''     <term>
  209. '''       <see cref="ContentAlignment.MiddleCenter"/>
  210. '''     </term>
  211. '''     <description><para></para><paramref name="margin"/> is ignored.</description>
  212. '''   </item>
  213. ''' </list>
  214. ''' </param>
  215. '''
  216. ''' <param name="font">
  217. ''' Optional. A custom <see cref="Font"/> to use. If not provided, a bold <c>Arial</c> font is used.
  218. ''' <para></para>
  219. ''' Note: Custom font size (<see cref="System.Drawing.Font.Size"/>) is ignored. It is determined by <paramref name="scale"/> parameter.
  220. ''' </param>
  221. '''
  222. ''' <param name="textColor">
  223. ''' Optional. The color of the text.
  224. ''' <para></para>
  225. ''' Default value is <see cref="Color.White"/>.
  226. ''' </param>
  227. '''
  228. ''' <param name="outlineColor">
  229. ''' Optional. The color of the text outline.
  230. ''' <para></para>
  231. ''' Default value is <see cref="Color.Black"/>.
  232. ''' </param>
  233. '''
  234. ''' <param name="outlineThickness">
  235. ''' Optional. The thickness of the outline, in pixels.
  236. ''' <para></para>
  237. ''' Default value is 2 pixels.
  238. ''' </param>
  239. <DebuggerStepThrough>
  240. <Extension>
  241. <EditorBrowsable(EditorBrowsableState.Always)>
  242. Public Sub DrawTextScaled(ByRef refImg As Image, text As String, scale As Single,
  243.                      position As ContentAlignment, margin As Single,
  244.                      Optional font As Font = Nothing,
  245.                      Optional textColor As Color = Nothing,
  246.                      Optional outlineColor As Color = Nothing,
  247.                      Optional outlineThickness As Short = 2)
  248.  
  249.    If margin < 0 Then
  250.        Throw New ArgumentOutOfRangeException(NameOf(margin), margin, "Margin must be greater than or equal to 0.")
  251.    End If
  252.  
  253.    If scale < 1 Then
  254.        Throw New ArgumentOutOfRangeException(NameOf(scale), scale, "Font scale must be greater than or equal to 1.")
  255.    End If
  256.  
  257.    If textColor = Nothing Then
  258.        textColor = Color.White
  259.    End If
  260.  
  261.    If outlineColor = Nothing Then
  262.        outlineColor = Color.Black
  263.    End If
  264.  
  265.    Using g As Graphics = Graphics.FromImage(refImg)
  266.        g.SmoothingMode = SmoothingMode.AntiAlias
  267.        g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit
  268.        g.InterpolationMode = InterpolationMode.HighQualityBicubic
  269.        g.PixelOffsetMode = PixelOffsetMode.HighQuality
  270.        g.CompositingQuality = CompositingQuality.HighQuality
  271.  
  272.        Dim rawFontSize As Single = Math.Max(refImg.Width, refImg.Height) / scale
  273.        Dim maxAllowedFontSize As Single = Math.Min(refImg.Width, refImg.Height)
  274.        Dim fontSize As Single = Math.Min(rawFontSize, maxAllowedFontSize)
  275.  
  276.        Using textFont As Font =
  277.        If(font IsNot Nothing, New Font(font.FontFamily, fontSize, font.Style, GraphicsUnit.Pixel, font.GdiCharSet, font.GdiVerticalFont),
  278.                               New Font("Arial", fontSize, FontStyle.Bold, GraphicsUnit.Pixel))
  279.  
  280.            Dim textSize As SizeF = g.MeasureString(text, textFont)
  281.            Dim posX As Single = 0
  282.            Dim posY As Single = 0
  283.  
  284.            Select Case position
  285.                Case ContentAlignment.TopLeft
  286.                    posX = margin
  287.                    posY = margin
  288.  
  289.                Case ContentAlignment.TopCenter
  290.                    posX = (refImg.Width - textSize.Width) / 2
  291.                    posY = margin
  292.  
  293.                Case ContentAlignment.TopRight
  294.                    posX = refImg.Width - textSize.Width - margin
  295.                    posY = margin
  296.  
  297.                Case ContentAlignment.MiddleLeft
  298.                    posX = margin
  299.                    posY = (refImg.Height - textSize.Height) / 2
  300.  
  301.                Case ContentAlignment.MiddleCenter
  302.                    posX = (refImg.Width - textSize.Width) / 2
  303.                    posY = (refImg.Height - textSize.Height) / 2
  304.  
  305.                Case ContentAlignment.MiddleRight
  306.                    posX = refImg.Width - textSize.Width - margin
  307.                    posY = (refImg.Height - textSize.Height) / 2
  308.  
  309.                Case ContentAlignment.BottomLeft
  310.                    posX = margin
  311.                    posY = refImg.Height - textSize.Height - margin
  312.  
  313.                Case ContentAlignment.BottomCenter
  314.                    posX = (refImg.Width - textSize.Width) / 2
  315.                    posY = refImg.Height - textSize.Height - margin
  316.  
  317.                Case ContentAlignment.BottomRight
  318.                    posX = refImg.Width - textSize.Width - margin
  319.                    posY = refImg.Height - textSize.Height - margin
  320.  
  321.                Case Else
  322.                    Throw New InvalidEnumArgumentException(NameOf(position), position, GetType(ContentAlignment))
  323.            End Select
  324.  
  325.            Using outlineBrush As New SolidBrush(outlineColor)
  326.  
  327.                For dx As Short = -outlineThickness To outlineThickness
  328.                    For dy As Short = -outlineThickness To outlineThickness
  329.                        If dx <> 0 OrElse dy <> 0 Then
  330.                            g.DrawString(text, textFont, outlineBrush, posX + dx, posY + dy)
  331.                        End If
  332.                    Next dy
  333.                Next dx
  334.            End Using
  335.  
  336.            Using textBrush As New SolidBrush(textColor)
  337.                g.DrawString(text, textFont, textBrush, posX, posY)
  338.            End Using
  339.        End Using ' font
  340.    End Using ' g
  341. End Sub
  342.  
  343. ''' <summary>
  344. ''' Draws a number onto the specified <see cref="Image"/> at a given position and scale factor.
  345. ''' </summary>
  346. '''
  347. ''' <param name="refImg">
  348. ''' The <see cref="Image"/> to modify. The number will be drawn directly on this image.
  349. ''' </param>
  350. '''
  351. ''' <param name="number">
  352. ''' The number to draw on the image.
  353. ''' </param>
  354. '''
  355. ''' <param name="scale">
  356. ''' The relative image scale factor to determine font size. Lower values increase the size of the text.
  357. ''' <para></para>
  358. ''' Suggested value is from 10 to 20.
  359. ''' </param>
  360. '''
  361. ''' <param name="position">
  362. ''' The position/alignment where the number should be drawn (e.g., bottom-right).
  363. ''' </param>
  364. '''
  365. ''' <param name="margin">
  366. ''' The margin (in pixels) from the edge of the image to position the text.
  367. ''' <para></para>
  368. ''' This value has different meaning depending on <paramref name="position"/> parameter:
  369. ''' <para></para>
  370. ''' <list type="bullet">
  371. '''   <item>
  372. '''     <term>
  373. '''       <see cref="ContentAlignment.TopLeft"/>, <see cref="ContentAlignment.TopRight"/>,
  374. '''       <para></para>
  375. '''       <see cref="ContentAlignment.BottomLeft"/> and <see cref="ContentAlignment.BottomRight"/>
  376. '''     </term>
  377. '''     <description><para></para><paramref name="margin"/> specifies the diagonal offset.</description>
  378. '''   </item>
  379. '''   <item>
  380. '''     <term>
  381. '''       <see cref="ContentAlignment.MiddleLeft"/> and <see cref="ContentAlignment.MiddleRight"/>
  382. '''     </term>
  383. '''     <description><para></para><paramref name="margin"/> specifies the horizontal offset.</description>
  384. '''   </item>
  385. '''   <item>
  386. '''     <term>
  387. '''       <see cref="ContentAlignment.TopCenter"/> and <see cref="ContentAlignment.BottomCenter"/>
  388. '''     </term>
  389. '''     <description><para></para><paramref name="margin"/> specifies the vertical offset.</description>
  390. '''   </item>
  391. '''   <item>
  392. '''     <term>
  393. '''       <see cref="ContentAlignment.MiddleCenter"/>
  394. '''     </term>
  395. '''     <description><para></para><paramref name="margin"/> is ignored.</description>
  396. '''   </item>
  397. ''' </list>
  398. ''' </param>
  399. '''
  400. ''' <param name="font">
  401. ''' Optional. A custom <see cref="Font"/> to use. If not provided, a bold <c>Arial</c> font is used.
  402. ''' <para></para>
  403. ''' Note: Custom font size (<see cref="System.Drawing.Font.Size"/>) is ignored. It is determined by <paramref name="scale"/> parameter.
  404. ''' </param>
  405. '''
  406. ''' <param name="textColor">
  407. ''' Optional. The color of the text.
  408. ''' <para></para>
  409. ''' Default value is <see cref="Color.White"/>.
  410. ''' </param>
  411. '''
  412. ''' <param name="outlineColor">
  413. ''' Optional. The color of the text outline.
  414. ''' <para></para>
  415. ''' Default value is <see cref="Color.Black"/>.
  416. ''' </param>
  417. '''
  418. ''' <param name="outlineThickness">
  419. ''' Optional. The thickness of the outline, in pixels.
  420. ''' <para></para>
  421. ''' Default value is 2 pixels.
  422. ''' </param>
  423. <DebuggerStepThrough>
  424. <Extension>
  425. <EditorBrowsable(EditorBrowsableState.Always)>
  426. Public Sub DrawNumberScaled(ByRef refImg As Image, number As Integer, scale As Single,
  427.                        position As ContentAlignment, margin As Single,
  428.                        Optional font As Font = Nothing,
  429.                        Optional textColor As Color = Nothing,
  430.                        Optional outlineColor As Color = Nothing,
  431.                        Optional outlineThickness As Short = 2)
  432.  
  433.    DrawTextScaled(refImg, CStr(number), scale, position, margin, font, textColor, outlineColor, outlineThickness)
  434. End Sub
  435.  
« Última modificación: Hoy a las 01:49 por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.926



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #596 en: Hoy a las 01:41 »

Cuatro métodos de extensión para el tipo DateTime con los que obtener una representación de fecha o fecha y hora realmente amistosa.

Ejemplos:

  Fecha en inglés: 11 May, 2025
  Fecha en español: 11 de mayo de 2025
  Fecha en alemán: 11. Mai 2025

  Fecha y hora en inglés: 11 May, 2025 at 23:59:59
  Fecha y hora en español: 11 de mayo de 2025 a las 23:59:59

No soy experto en la representación por escrito de fechas en otros idiomas así que solo intenté perfeccionar estos tres. La representación en alemán estaría bien según me he informado, ya que se supone que se añade un punto de esa forma. En definitiva, creo que para ir tirando está bien así.

Código
  1. ''' <summary>
  2. ''' Converts a <see cref="Date"/> object to a long friendly date string based on the current culture.
  3. ''' <para></para>
  4. ''' For example:
  5. ''' <list type="bullet">
  6. '''   <item><description>English<para></para>11 May, 2025</description></item>
  7. '''   <item><description>Spanish<para></para>11 de mayo de 2025</description></item>
  8. '''   <item><description>German<para></para>11. Mai 2025</description></item>
  9. ''' </list>
  10. ''' </summary>
  11. '''
  12. ''' <param name="[date]">
  13. ''' The <see cref="Date"/> object to be formatted.
  14. ''' </param>
  15. '''
  16. ''' <returns>
  17. ''' A string representing the formatted date, based on the current culture.
  18. ''' </returns>
  19. <DebuggerStepThrough>
  20. <Extension>
  21. <EditorBrowsable(EditorBrowsableState.Always)>
  22. Public Function ToLongFriendlyDateString([date] As Date) As String
  23.  
  24.    Return DateExtensions.ToLongFriendlyDateString([date], CultureInfo.CurrentCulture)
  25. End Function
  26.  
  27. ''' <summary>
  28. ''' Converts a <see cref="Date"/> object to a long friendly date string based on the specified culture.
  29. ''' <para></para>
  30. ''' For example:
  31. ''' <list type="bullet">
  32. '''   <item><description>English<para></para>11 May, 2025</description></item>
  33. '''   <item><description>Spanish<para></para>11 de mayo de 2025</description></item>
  34. '''   <item><description>German<para></para>11. Mai 2025</description></item>
  35. ''' </list>
  36. ''' </summary>
  37. '''
  38. ''' <param name="[date]">
  39. ''' The <see cref="Date"/> object to be formatted.
  40. ''' </param>
  41. '''
  42. ''' <param name="provider">
  43. ''' The culture information used to format the date.
  44. ''' </param>
  45. '''
  46. ''' <returns>
  47. ''' A string representing the formatted date, based on the specified culture.
  48. ''' </returns>
  49. <DebuggerStepThrough>
  50. <Extension>
  51. <EditorBrowsable(EditorBrowsableState.Always)>
  52. Public Function ToLongFriendlyDateString([date] As Date, provider As IFormatProvider) As String
  53.  
  54.    Dim culture As CultureInfo = TryCast(provider, CultureInfo)
  55.    If culture IsNot Nothing Then
  56.  
  57.        Select Case culture.TwoLetterISOLanguageName.ToLower()
  58.            Case "es", "ca", "gl", "pt" ' Spanish, Catalonian, Galego, Portuguese
  59.                Return [date].ToString("dd 'de' MMMM 'de' yyyy", provider)
  60.  
  61.            Case "de" ' Deutsch
  62.                Return [date].ToString("dd'.' MMMM yyyy", provider)
  63.  
  64.            Case Else ' Do nothing.
  65.                Exit Select
  66.        End Select
  67.    End If
  68.  
  69.    Return [date].ToString("dd MMMM, yyyy", provider)
  70. End Function
  71.  
  72. ''' <summary>
  73. ''' Converts a <see cref="Date"/> object to a long friendly date string based on the current culture.
  74. ''' <para></para>
  75. ''' For example:
  76. ''' <list type="bullet">
  77. '''   <item><description>English<para></para>11 May, 2025 at 23:59:59</description></item>
  78. '''   <item><description>Spanish<para></para>11 de mayo de 2025 a las 23:59:59</description></item>
  79. ''' </list>
  80. ''' </summary>
  81. '''
  82. ''' <param name="[date]">
  83. ''' The <see cref="Date"/> object to be formatted.
  84. ''' </param>
  85. '''
  86. ''' <returns>
  87. ''' A string representing the formatted date, based on the current culture.
  88. ''' </returns>
  89. <DebuggerStepThrough>
  90. <Extension>
  91. <EditorBrowsable(EditorBrowsableState.Always)>
  92. Public Function ToLongFriendlyDateAndTimeString([date] As Date) As String
  93.  
  94.    Return DateExtensions.ToLongFriendlyDateAndTimeString([date], CultureInfo.CurrentCulture)
  95. End Function
  96.  
  97. ''' <summary>
  98. ''' Converts a <see cref="Date"/> object to a long friendly date string based on the specifies culture.
  99. ''' <para></para>
  100. ''' For example:
  101. ''' <list type="bullet">
  102. '''   <item><description>English<para></para>11 May, 2025 at 23:59:59</description></item>
  103. '''   <item><description>Spanish<para></para>11 de mayo de 2025 a las 23:59:59</description></item>
  104. ''' </list>
  105. ''' </summary>
  106. '''
  107. ''' <param name="[date]">
  108. ''' The <see cref="Date"/> object to be formatted.
  109. ''' </param>
  110. '''
  111. ''' <param name="provider">
  112. ''' The culture information used to format the date.
  113. ''' </param>
  114. '''
  115. ''' <returns>
  116. ''' A string representing the formatted date, based on the specified culture.
  117. ''' </returns>
  118. <DebuggerStepThrough>
  119. <Extension>
  120. <EditorBrowsable(EditorBrowsableState.Always)>
  121. Public Function ToLongFriendlyDateAndTimeString([date] As Date, provider As IFormatProvider) As String
  122.  
  123.    Dim culture As CultureInfo = TryCast(provider, CultureInfo)
  124.    If culture IsNot Nothing Then
  125.  
  126.        Select Case culture.TwoLetterISOLanguageName.ToLower()
  127.            Case "en" ' English
  128.                Return [date].ToString($"'{ToLongFriendlyDateString([date], provider)}' 'at' HH:mm:ss", provider)
  129.  
  130.            Case "es" ' Spanish
  131.                Return [date].ToString($"'{ToLongFriendlyDateString([date], provider)}' 'a las' HH:mm:ss", provider)
  132.  
  133.            Case Else ' Do nothing.
  134.                Exit Select
  135.        End Select
  136.    End If
  137.  
  138.    Return [date].ToString($"'{ToLongFriendlyDateString([date], provider)}' '—' HH:mm:ss", provider)
  139. End Function
« Última modificación: Hoy a las 03:14 por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.926



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #597 en: Hoy a las 18:11 »

Librería .NET para automatizar el uso de rar.exe de RARLab (WinRAR)

Esto es un wrapper .NET completo para la herramienta por línea de comandos rar.exe oficial de RARLab. Esta librería permite a los desarrolladores de .NET acceder y controlar fácilmente casi todas las funciones de rar.exe, como comprimir, extraer, listar, testar, crear volúmenes de recuperación y administrar archivos RAR, desde sus aplicaciones.

Llevaba mucho tiempo queriendo hacer esto, bastantes años hace que se me ocurrió la idea por que hay infinidad de librerías disponibles en la mayoría de lenguajes de programación para manejar formatos ZIP y 7Zip entre otros muchos, pero para el formato RAR, en especial el formato RARv5 son muy escasas... probablemente por desinterés y/o por ser un formato privativo. Lo cierto es que no conozco ningún otro wrapper del executable rar.exe, ni tampoco un wrapper que en lugar de depender de rar.exe haga llamadas nativas a una librería oficial de RARLab.

El caso es que nunca empecé este proyecto por simple pereza. Me parecía muy interesante pero al mismo tiempo no me resultaba necesario en realidad desarrollar una infraestructura completa para configurar el lanzamiento del proceso de rar.exe pasándole un comando cualquiera, cosa que podía escribir en una sola línea como esta: Process.Start(".\rar.exe", "argumentos") — pero claro, esto es algo muy codificado en el código por así decirlo, no es tan bonito o elegante o profesional como configurar una sofisticada clase para construir los argumentos y controlar el lanzamiento del proceso con sus códigos de salida y demás.

Así que siempre lo estuve aplazando. Y cuando finalmente decidí empezar, hace cosa de unas semanas, esperaba poder compartirlo con ustedes en formato de "snippet" en este hilo, es decir algo de un tamaño reducido, pero fui demasiado ingenuo ya que al final el trabajo ha alcanzado la cantidad de 9 clases para representar diversos comandos, 17 enumeraciones y otras tantas clases para otros elementos integrados, haciendo un total de 37 archivos separados de código fuente.

Así que no me ha quedado más remedio que compartirlo en GitHub, y aquí lo comparto con ustedes:

  👉 📦 RARLab's rar.exe .NET Wrapper Library

Como he dicho, esto es una librería, un archivo dll para administrar el uso del archivo rar.exe. Es totalmente "universal", se puede usar en proyectos de VB.NET o de C#, bajo .NET Framework o NET 5.0+ (el proyecto habría que migrarlo), no hay dependencias más allá del archivo 'rar.exe' de WinRAR y la licencia del producto, que deben ser administrados por el usuario.



El README.md del repositorio en GitHub incluye un ejemplo de uso para VB.NET y también para C#.

Además, en el código fuente de todas las nueve clases que representan los 'Comandos', incluyen un apartado, arriba del todo de la clase, con un ejemplo de uso para VB.NET, y también en la propia documentación XML de la clase.

De todas formas, aquí les dejo un ejemplo de uso completo para VB.NET

 — Construir un Comando para la creación de archivos RAR utilizando la clase RarCreationCommand:

Código
  1. Imports DevCase.RAR
  2. Imports DevCase.RAR.Commands

Código
  1. Dim archivePath As String = "C:\New Archive.rar"
  2. Dim filesToAdd As String = "C:\Directory to add\"
  3.  
  4. Dim command As New RarCreationCommand(RarCreationMode.Add, archivePath, filesToAdd) With {
  5.    .RarExecPath = ".\rar.exe",
  6.    .RarLicenseData = "(Your license key)",
  7.    .RecurseSubdirectories = True,
  8.    .EncryptionProperties = Nothing,
  9.    .SolidCompression = False,
  10.    .CompressionMode = RarCompressionMode.Normal,
  11.    .DictionarySize = RarDictionarySize.Mb__128,
  12.    .OverwriteMode = RarOverwriteMode.Overwrite,
  13.    .FilePathMode = RarFilePathMode.ExcludeBaseDirFromFileNames,
  14.    .FileTimestamps = RarFileTimestamps.All,
  15.    .AddQuickOpenInformation = TriState.True,
  16.    .ProcessHardLinksAsLinks = True,
  17.    .ProcessSymbolicLinksAsLinks = TriState.True,
  18.    .DuplicateFileMode = RarDuplicateFileMode.Enabled,
  19.    .FileChecksumMode = RarFileChecksumMode.BLAKE2sp,
  20.    .ArchiveComment = New RarArchiveComment("Hello world!"),
  21.    .RecoveryRecordPercentage = 0,
  22.    .VolumeSplitOptions = Nothing,
  23.    .FileTypesToStore = Nothing
  24. }

 — Para obtener los argumentos completos de la línea de comandos de nuestro Comando:

Código
  1. Console.WriteLine($"Command-line arguments: {command}")
Código
  1. MessageBox.Show(command.ToString())

 — Ejecutar nuestro Comando usando la clase RarCommandExecutor:

Código
  1. Using rarExecutor As New RarCommandExecutor(command)
  2.  
  3.    AddHandler rarExecutor.OutputDataReceived,
  4.        Sub(sender As Object, e As DataReceivedEventArgs)
  5.            Console.WriteLine($"[Output] {Date.Now:yyyy-MM-dd HH:mm:ss} - {e.Data}")
  6.        End Sub
  7.  
  8.    AddHandler rarExecutor.ErrorDataReceived,
  9.        Sub(sender As Object, e As DataReceivedEventArgs)
  10.            If e.Data IsNot Nothing Then
  11.                Console.WriteLine($"[Error] {Date.Now:yyyy-MM-dd HH:mm:ss} - {e.Data}")
  12.            End If
  13.        End Sub
  14.  
  15.    AddHandler rarExecutor.Exited,
  16.        Sub(sender As Object, e As EventArgs)
  17.            Dim pr As Process = DirectCast(sender, Process)
  18.            Dim rarExitCode As RarExitCode = DirectCast(pr.ExitCode, RarExitCode)
  19.            Console.WriteLine($"[Exited] {Date.Now:yyyy-MM-dd HH:mm:ss} - rar.exe process has terminated with exit code {pr.ExitCode} ({rarExitCode})")
  20.        End Sub
  21.  
  22.    Dim exitcode As RarExitCode = rarExecutor.ExecuteRarAsync().Result
  23. End Using
« Última modificación: Hoy a las 19:37 por Eleкtro » En línea



Páginas: 1 ... 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 [60] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines