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

 

 


Tema destacado: Trabajando con las ramas de git (tercera parte)


+  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 2 Visitantes están viendo este tema.
Páginas: 1 ... 44 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 526,911 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

Dos simples métodos para ocultar y restaurar las cabeceras de las pestañas de un TabControl:



Código
  1. ''' <summary>
  2. ''' Provides extension methods for the <see cref="TabControl"/> class.
  3. ''' </summary>
  4. <HideModuleName>
  5. Public Module TabControlExtensions
  6.  
  7.    ''' ---------------------------------------------------------------------------------------------------
  8.    ''' <summary>
  9.    ''' Hides the tab headers of the source <see cref="TabControl"/>.
  10.    ''' </summary>
  11.    ''' ---------------------------------------------------------------------------------------------------
  12.    ''' <example> This is a code example.
  13.    ''' <code language="VB">
  14.    ''' ' Create a TabControl instance
  15.    ''' Dim myTabControl As New TabControl()
  16.    '''
  17.    ''' ' Add some tabs to the TabControl
  18.    ''' myTabControl.TabPages.Add("Tab 1")
  19.    ''' myTabControl.TabPages.Add("Tab 2")
  20.    ''' myTabControl.TabPages.Add("Tab 3")
  21.    '''
  22.    ''' ' Display the TabControl in a Form
  23.    ''' Me.Controls.Add(myTabControl)
  24.    ''' myTabControl.BringToFront()
  25.    '''
  26.    ''' ' Hide the tab headers
  27.    ''' myTabControl.HideTabheaders()
  28.    ''' </code>
  29.    ''' </example>
  30.    ''' ---------------------------------------------------------------------------------------------------
  31.    ''' <param name="tabControl">
  32.    ''' The <see cref="TabControl"/> whose tab headers are to be hidden.
  33.    ''' </param>
  34.    ''' ---------------------------------------------------------------------------------------------------
  35.    <Extension>
  36.    <DebuggerStepThrough>
  37.    Public Sub HideTabheaders(tabControl As TabControl)
  38.        TabControlExtensions.ShowTabheaders(tabControl, TabSizeMode.Fixed, New Size(0, 1))
  39.    End Sub
  40.  
  41.    ''' ---------------------------------------------------------------------------------------------------
  42.    ''' <summary>
  43.    ''' Shows the tab headers of the source <see cref="TabControl"/>.
  44.    ''' </summary>
  45.    ''' ---------------------------------------------------------------------------------------------------
  46.    ''' <example> This is a code example.
  47.    ''' <code language="VB">
  48.    ''' ' Create a TabControl instance
  49.    ''' Dim myTabControl As New TabControl()
  50.    '''
  51.    ''' ' Add some tabs to the TabControl
  52.    ''' myTabControl.TabPages.Add("Tab 1")
  53.    ''' myTabControl.TabPages.Add("Tab 2")
  54.    ''' myTabControl.TabPages.Add("Tab 3")
  55.    '''
  56.    ''' ' Display the TabControl in a Form
  57.    ''' Me.Controls.Add(myTabControl)
  58.    ''' myTabControl.BringToFront()
  59.    '''
  60.    ''' ' Hide the tab headers
  61.    ''' myTabControl.HideTabheaders()
  62.    '''
  63.    ''' ' Show the tab headers with custom item size and filling to the right
  64.    ''' myTabControl.ShowTabheaders(TabSizeMode.Normal, New Size(100, 50))
  65.    ''' </code>
  66.    ''' </example>
  67.    ''' ---------------------------------------------------------------------------------------------------
  68.    ''' <param name="tabControl">
  69.    ''' The <see cref="TabControl"/> whose tab headers are to be shown.
  70.    ''' </param>
  71.    '''
  72.    ''' <param name="sizeMode">
  73.    ''' A value from <see cref="TabSizeMode"/> enumeration, that specifies the way that the control's tabs are sized.
  74.    ''' </param>
  75.    '''
  76.    ''' <param name="itemSize">
  77.    ''' Optional. The size of each tab header.
  78.    ''' <para></para>
  79.    ''' Default is <see cref="Size.Empty"/>, which is used to let the control automatically calculate the proper size
  80.    ''' when <paramref name="sizeMode"/> is <see cref="TabSizeMode.Normal"/> or <see cref="TabSizeMode.FillToRight"/>.
  81.    ''' </param>
  82.    ''' ---------------------------------------------------------------------------------------------------
  83.    <Extension>
  84.    <DebuggerStepThrough>
  85.    Public Sub ShowTabheaders(tabControl As TabControl, sizeMode As TabSizeMode, Optional itemSize As Size = Nothing)
  86.        If itemSize = Nothing Then
  87.            If sizeMode = TabSizeMode.Fixed Then
  88.                Throw New ArgumentException("Value can't be null for fixed size mode.", paramName:=NameOf(itemSize))
  89.            End If
  90.            itemSize = Size.Empty
  91.        End If
  92.  
  93.        With tabControl
  94.            .SuspendLayout()
  95.            .ItemSize = itemSize
  96.            .SizeMode = sizeMode
  97.            .ResumeLayout(performLayout:=True)
  98.        End With
  99.    End Sub
  100.  
  101. End Module

Modo de empleo utilizado en la imagen de demostración:
Código
  1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  2.    Me.TabControl1.HideTabheaders()
  3. End Sub
  4.  
  5. Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  6.    Me.TabControl1.ShowTabheaders(TabSizeMode.Normal)
  7. End Sub


« Última modificación: 11 Abril 2024, 02:30 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

Les traigo una clase que he desarrollado, por nombre ToolStripCheckBox, cuyo nombre es autoexplicativo, pues se trata de un CheckBox que podemos usar en un componente ToolStrip y StatusStrip:





Código
  1. #Region " Imports "
  2.  
  3. Imports System.ComponentModel
  4. Imports System.ComponentModel.Design
  5. Imports System.Runtime.InteropServices
  6. Imports System.Windows.Forms.Design
  7.  
  8. #End Region
  9.  
  10. #Region " ToolStripCheckBox "
  11.  
  12. ''' <summary>
  13. ''' Represents a selectable <see cref="ToolStripItem"/> that when clicked, toggles a checkmark.
  14. ''' </summary>
  15. ''' <seealso cref="ToolStripControlHost"/>
  16. <
  17.    ClassInterface(ClassInterfaceType.AutoDispatch),
  18.    ComVisible(True),
  19.    DebuggerStepThrough,
  20.    DefaultEvent(NameOf(ToolStripCheckBox.CheckedChanged)),
  21.    DefaultProperty(NameOf(ToolStripCheckBox.Text)),
  22.    Description("Represents a selectable ToolStripItem that when clicked, toggles a checkmark."),
  23.    Designer("System.Windows.Forms.Design.ToolStripItemDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
  24.    DesignerCategory(NameOf(DesignerCategoryAttribute.Generic)),
  25.    DesignTimeVisible(False),
  26.    DisplayName(NameOf(ToolStripCheckBox)),
  27.    Localizable(True),
  28.    ToolboxBitmap(GetType(CheckBox), "CheckBox.bmp"),
  29.    ToolboxItem(False),
  30.    ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Allow),
  31.    ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip Or ToolStripItemDesignerAvailability.StatusStrip)
  32. >
  33. Public Class ToolStripCheckBox : Inherits ToolStripControlHost
  34.  
  35. #Region " Properties "
  36.  
  37.    ''' <summary>
  38.    ''' Gets the <see cref="CheckBox"/> control that is hosted by this <see cref="ToolStripCheckBox"/>.
  39.    ''' </summary>
  40.    <
  41.        Browsable(True), EditorBrowsable(EditorBrowsableState.Advanced),
  42.        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
  43.        Category("Hosted"), Description("The CheckBox control that is hosted by this control.")
  44.    >
  45.    Public Shadows ReadOnly Property Control As CheckBox
  46.        Get
  47.            Return DirectCast(MyBase.Control, CheckBox)
  48.        End Get
  49.    End Property
  50.  
  51.    ''' <summary>
  52.    ''' Gets or sets a value indicating whether this <see cref="ToolStripCheckBox"/> is in the checked state.
  53.    ''' </summary>
  54.    '''
  55.    ''' <returns>
  56.    ''' <see langword="True"/> if checked; otherwise, <see langword="False"/>.
  57.    ''' </returns>
  58.    <
  59.        Bindable(True), SettingsBindable(True),
  60.        DefaultValue(False),
  61.        RefreshProperties(RefreshProperties.All),
  62.        Category("Appearance"), Description("Specifies whether this control is in the checked state.")
  63.    >
  64.    Public Property Checked As Boolean
  65.        Get
  66.            Return Me.Control.Checked
  67.        End Get
  68.        Set(value As Boolean)
  69.            Me.Control.Checked = value
  70.        End Set
  71.    End Property
  72.  
  73.    ''' <summary>
  74.    ''' Gets or sets the checked state of this <see cref="ToolStripCheckBox"/>.
  75.    ''' </summary>
  76.    '''
  77.    ''' <returns>
  78.    ''' One of the <see cref="System.Windows.Forms.CheckState"/> enumeration values.
  79.    ''' <para></para>
  80.    ''' The default value is <see cref="System.Windows.Forms.CheckState.Unchecked"/>.
  81.    ''' </returns>
  82.    '''
  83.    ''' <exception cref="System.ComponentModel.InvalidEnumArgumentException">
  84.    ''' The value assigned is not one of the <see cref="System.Windows.Forms.CheckState"/> enumeration values.
  85.    ''' </exception>
  86.    <
  87.        Bindable(True),
  88.        DefaultValue(CheckState.Unchecked),
  89.        RefreshProperties(RefreshProperties.All),
  90.        Category("Appearance"), Description("Specifies the checked state of this control.")
  91.    >
  92.    Public Property CheckState As CheckState
  93.        Get
  94.            Return Me.Control.CheckState
  95.        End Get
  96.        Set(value As CheckState)
  97.            Me.Control.CheckState = value
  98.        End Set
  99.    End Property
  100.  
  101.    ''' <summary>
  102.    ''' Gets or sets a value indicating whether this <see cref="ToolStripCheckBox"/>
  103.    ''' will allow three check states rather than two.
  104.    ''' </summary>
  105.    '''
  106.    ''' <remarks>
  107.    ''' If the <see cref="ToolStripCheckBox.ThreeState"/> property is set to <see langword="False"/>,
  108.    ''' the <see cref="ToolStripCheckBox.CheckState"/> property value can only be set to
  109.    ''' the <see cref="System.Windows.Forms.CheckState.Indeterminate"/> value in code,
  110.    ''' and not by user interaction doing click on the control.
  111.    ''' </remarks>
  112.    '''
  113.    ''' <returns>
  114.    ''' <see langword="True"/> if this <see cref="ToolStripCheckBox"/>
  115.    ''' is able to display three check states; otherwise, <see langword="False"/>.
  116.    ''' <para></para>
  117.    ''' The default value is <see langword="False"/>.
  118.    ''' </returns>
  119.    <
  120.        DefaultValue(False),
  121.        Category("Behavior"), Description("Specifies whether this control will allow three check states rather than two.")
  122.    >
  123.    Public Property ThreeState As Boolean
  124.        Get
  125.            Return Me.Control.ThreeState
  126.        End Get
  127.        Set(value As Boolean)
  128.            Me.Control.ThreeState = value
  129.        End Set
  130.    End Property
  131.  
  132. #End Region
  133.  
  134. #Region " Events "
  135.  
  136.    ''' <summary>
  137.    ''' Occurs whenever the <see cref="ToolStripCheckBox.Checked"/> property is changed.
  138.    ''' </summary>
  139.    Public Event CheckedChanged As EventHandler
  140.  
  141.    ''' <summary>
  142.    ''' Occurs whenever the <see cref="ToolStripCheckBox.CheckState"/> property is changed.
  143.    ''' </summary>
  144.    Public Event CheckStateChanged As EventHandler
  145.  
  146. #End Region
  147.  
  148. #Region " Constructors "
  149.  
  150.    ''' <summary>
  151.    ''' Initializes a new instance of the <see cref="ToolStripCheckBox"/> class.
  152.    ''' </summary>
  153.    Public Sub New()
  154.  
  155.        MyBase.New(New CheckBox())
  156.        Me.Control.BackColor = Color.Transparent
  157.    End Sub
  158.  
  159. #End Region
  160.  
  161. #Region " Event Invocators "
  162.  
  163.    ''' <summary>
  164.    ''' Raises the <see cref="ToolStripCheckBox.CheckedChanged"/> event.
  165.    ''' </summary>
  166.    '''
  167.    ''' <param name="sender">
  168.    ''' The source of the event.
  169.    ''' </param>
  170.    '''
  171.    ''' <param name="e">
  172.    ''' The <see cref="EventArgs"/> instance containing the event data.
  173.    ''' </param>
  174.    Private Sub OnCheckedChanged(sender As Object, e As EventArgs)
  175.        If Me.CheckedChangedEvent IsNot Nothing Then
  176.            RaiseEvent CheckedChanged(Me, e)
  177.        End If
  178.    End Sub
  179.  
  180.    ''' <summary>
  181.    ''' Raises the <see cref="ToolStripCheckBox.CheckStateChanged"/> event.
  182.    ''' </summary>
  183.    '''
  184.    ''' <param name="sender">
  185.    ''' The source of the event.
  186.    ''' </param>
  187.    '''
  188.    ''' <param name="e">
  189.    ''' The <see cref="EventArgs"/> instance containing the event data.
  190.    ''' </param>
  191.    Private Sub OnCheckStateChanged(sender As Object, e As EventArgs)
  192.        If Me.CheckStateChangedEvent IsNot Nothing Then
  193.            RaiseEvent CheckStateChanged(Me, e)
  194.        End If
  195.    End Sub
  196.  
  197. #End Region
  198.  
  199. #Region " Event Invocators (Overriden) "
  200.  
  201.    ''' <summary>
  202.    ''' Subscribes events from the hosted control
  203.    ''' </summary>
  204.    '''
  205.    ''' <param name="control">
  206.    ''' The control from which to subscribe events.
  207.    ''' </param>
  208.    Protected Overrides Sub OnSubscribeControlEvents(control As Control)
  209.        MyBase.OnSubscribeControlEvents(control)
  210.        AddHandler DirectCast(control, CheckBox).CheckedChanged, AddressOf Me.OnCheckedChanged
  211.    End Sub
  212.  
  213.    ''' <summary>
  214.    ''' Unsubscribes events from the hosted control
  215.    ''' </summary>
  216.    '''
  217.    ''' <param name="control">
  218.    ''' The control from which to unsubscribe events.
  219.    ''' </param>
  220.    Protected Overrides Sub OnUnsubscribeControlEvents(control As Control)
  221.        MyBase.OnUnsubscribeControlEvents(control)
  222.        RemoveHandler DirectCast(control, CheckBox).CheckedChanged, AddressOf Me.OnCheckedChanged
  223.    End Sub
  224.  
  225.    ''' <summary>
  226.    ''' Raises the <see cref="Windows.Forms.Control.ParentChanged"/> event.
  227.    ''' </summary>
  228.    '''
  229.    ''' <param name="oldParent">
  230.    ''' The original parent of the item.
  231.    ''' </param>
  232.    '''
  233.    ''' <param name="newParent">
  234.    ''' The new parent of the item.
  235.    ''' </param>
  236.    Protected Overrides Sub OnParentChanged(oldParent As ToolStrip, newParent As ToolStrip)
  237.        MyBase.OnParentChanged(oldParent, newParent)
  238.    End Sub
  239.  
  240.    ''' <summary>
  241.    ''' Raises the <see cref="ToolStripItem.OwnerChanged"/> event.
  242.    ''' </summary>
  243.    '''
  244.    ''' <param name="e">
  245.    ''' The <see cref="EventArgs"/> instance containing the event data.
  246.    ''' </param>
  247.    Protected Overrides Sub OnOwnerChanged(e As EventArgs)
  248.        MyBase.OnOwnerChanged(e)
  249.    End Sub
  250.  
  251. #End Region
  252.  
  253. End Class
  254.  
  255. #End Region


« Última modificación: 11 Abril 2024, 12:25 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #582 en: 11 Abril 2024, 12:59 pm »

Un simple validador de rutas de archivos y directorios para operaciones de arrastrar y soltar (Drag&Drop) sobre un control, que nos permite indicar si se debe permitir arrastrar múltiples rutas, y opcionalmente la extensión de los archivos que se deben permitir.

El método de validación es sencillo de adaptar a otros escenarios, y nos puede ahorrar mucho tiempo repitiendo código para este tipo de validaciones.

Código
  1. ''' <summary>
  2. ''' Specifies the type of paths that can be dragged in a drag&amp;drop operation.
  3. ''' </summary>
  4. Public Enum PathDragType
  5.  
  6.        ''' <summary>
  7.        ''' Only files can be dragged.
  8.        ''' </summary>
  9.        Files
  10.  
  11.        ''' <summary>
  12.        ''' Only directories can be dragged.
  13.        ''' </summary>
  14.        Directories
  15.  
  16.        ''' <summary>
  17.        ''' Both files and directories can be dragged.
  18.        ''' </summary>
  19.        Any
  20.  
  21. End Enum
  22.  
  23. ''' <summary>
  24. ''' Validates the <see cref="IDataObject"/> for a file or directory drag operation,
  25. ''' and returns the appropriate <see cref="DragDropEffects"/>.
  26. ''' <para></para>
  27. ''' This function should be called on the <see cref="Control.DragEnter"/> event handler of a control,
  28. ''' to assign its return value for the <see cref="DragEventArgs.Effect"/> property.
  29. ''' </summary>
  30. '''
  31. ''' <example> This is a code example that shows how to validate a drag operation for a single file matching the specified file extensions.
  32. ''' <code language="VB">
  33. ''' Private Sub TextBox1_DragEnter(sender As Object, e As DragEventArgs) Handles TextBox1.DragEnter
  34. '''
  35. '''     Dim allowedFileExtensions As String() = {"avi", "mkv", "mp4"}
  36. '''     e.Effect = ValidatePathDrag(e.Data, PathDragType.Files, allowMultiplePaths:=False, allowedFileExtensions)
  37. ''' End Sub
  38. '''
  39. ''' Private Sub TextBox1_DragDrop(sender As Object, e As DragEventArgs) Handles TextBox1.DragDrop
  40. '''
  41. '''     If e.Data.GetDataPresent(DataFormats.FileDrop) AndAlso e.Effect = DragDropEffects.Copy Then
  42. '''         Dim singleFilePath As String = DirectCast(e.Data.GetData(DataFormats.FileDrop), String()).SingleOrDefault()
  43. '''
  44. '''         Dim tb As TextBox = DirectCast(sender, TextBox)
  45. '''         tb.Text = singleFilePath
  46. '''     End If
  47. ''' End Sub
  48. ''' </code>
  49. ''' </example>
  50. '''
  51. ''' <param name="data">
  52. ''' The source <see cref="IDataObject"/> object to validate,
  53. ''' typically the object retrieved from <see cref="DragEventArgs.Data"/> property.
  54. ''' </param>
  55. '''
  56. ''' <param name="allowedDragType">
  57. ''' A <see cref="PathDragType"/> value that indicates the
  58. ''' type of paths allowed for the drag operation (files, directories, or any).
  59. ''' </param>
  60. '''
  61. ''' <param name="allowMultiplePaths">
  62. ''' A <see cref="Boolean"/> value indicating whether dragging multiple paths are allowed for the drag operation.
  63. ''' <para></para>
  64. ''' If this value is <see langword="False"/> and the <paramref name="data"/> object
  65. ''' contains multiple paths, <see cref="DragDropEffects.None"/> is returned.
  66. ''' </param>
  67. '''
  68. ''' <param name="allowedFileExtensions">
  69. ''' Optional. An array of file extensions to allow in a file drag operation. By default, all file extensions are allowed.
  70. ''' <para></para>
  71. ''' If any of the file paths contained in the <paramref name="data"/> object does not match
  72. ''' the specified allowed file extensions, <see cref="DragDropEffects.None"/> is returned.
  73. ''' <para></para>
  74. ''' This parameter has no effect for directories contained in the <paramref name="data"/> object.
  75. ''' </param>
  76. '''
  77. ''' <returns>
  78. ''' Returns <see cref="DragDropEffects.Copy"/> If the drag validation was successful;
  79. ''' otherwise, returns <see cref="DragDropEffects.None"/>.
  80. ''' </returns>
  81. <DebuggerStepThrough>
  82. Public Shared Function ValidatePathDrag(data As IDataObject,
  83.                                        allowedDragType As PathDragType,
  84.                                        allowMultiplePaths As Boolean,
  85.                                        ParamArray allowedFileExtensions As String()) As DragDropEffects
  86.  
  87.    Dim dataObject As DataObject = DirectCast(data, DataObject)
  88.    If dataObject.ContainsFileDropList() Then
  89.        Dim filePathList As New List(Of String)
  90.        Dim pathList As StringCollection = dataObject.GetFileDropList()
  91.        Dim pathListlength As Integer = pathList.Count
  92.  
  93.        ' Single/multiple path validation.
  94.        If (Not allowMultiplePaths AndAlso pathListlength > 1) Then
  95.            Return DragDropEffects.None
  96.        End If
  97.  
  98.        Select Case allowedDragType
  99.  
  100.            ' Fails if path list contains any file.
  101.            Case PathDragType.Directories
  102.                For Each path As String In pathList
  103.                    If File.Exists(path) Then
  104.                        Return DragDropEffects.None
  105.                    End If
  106.                Next
  107.  
  108.            ' Fails if path list contains any directory.
  109.            Case PathDragType.Files, PathDragType.Any
  110.                For Each path As String In pathList
  111.                    If Directory.Exists(path) Then
  112.                        Return DragDropEffects.None
  113.                    End If
  114.                    ' Build the list of file paths, excluding any directory from the path list.
  115.                    filePathList.Add(path)
  116.                Next
  117.  
  118.        End Select
  119.  
  120.        If allowedFileExtensions?.Any() AndAlso filePathList.Any() Then
  121.            ' Trims the dot and white spaces to ensure that malformed file extension strings are corrected (eg. " .jpg"  -> "jpg").
  122.            Dim allowedFileExtensionsLower As IEnumerable(Of String) =
  123.                        From ext As String In allowedFileExtensions Select ext.TrimStart({"."c, " "c}).ToLower()
  124.  
  125.            For Each filePath As String In filePathList
  126.                ' Trims the dot from file extension strings (eg. ".jpg" -> "jpg").
  127.                Dim fileExtLower As String = IO.Path.GetExtension(filePath).TrimStart("."c).ToLower()
  128.                If Not allowedFileExtensionsLower.Contains(fileExtLower) Then
  129.                    Return DragDropEffects.None
  130.                End If
  131.            Next
  132.        End If
  133.  
  134.        Return DragDropEffects.Copy
  135.    End If
  136.  
  137.    Return DragDropEffects.None
  138. End Function
  139.  



Aquí muestro un ejemplo de uso, donde establezco que solamente se acepte arrastrar un archivo, y siempre y cuando ese archivo tenga la extensión avi, mp4 o mkv:

Código
  1. Private Sub TextBox1_DragEnter(sender As Object, e As DragEventArgs) Handles TextBox1.DragEnter
  2.    Dim allowedFileExtensions As String() = {"avi", "mkv", "mp4"}
  3.    e.Effect = ValidatePathDrag(e.Data, PathDragType.Files, allowMultiplePaths:=False, allowedFileExtensions)
  4. End Sub
  5.  
  6. Private Sub TextBox1_DragDrop(sender As Object, e As DragEventArgs) Handles TextBox1.DragDrop
  7.    Dim singleFilePath As String = DirectCast(e.Data.GetData(DataFormats.FileDrop), String()).Single()
  8.  
  9.    Dim tb As TextBox = DirectCast(sender, TextBox)
  10.    tb.Text = singleFilePath
  11. End Sub
« Última modificación: 11 Abril 2024, 18:36 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

Dos métodos de extensión para iterar todos los items (ToolStripItem) de un control de tipo ToolStrip, StatusStrip, MenuStrip o ContextMenuStrip, opcionalmente de forma recursiva (sin recursión de método), y llevar a cabo una acción específica sobre cada item:

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 12-April-2024
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' ToolStrip.ForEachItem(Boolean, Action(Of ToolStripItem))
  9. ' ToolStrip.ForEachItem(Of T As ToolStripItem)(Boolean, Action(Of T))
  10.  
  11. #End Region
  12.  
  13. #Region " Option Statements "
  14.  
  15. Option Strict On
  16. Option Explicit On
  17. Option Infer Off
  18.  
  19. #End Region
  20.  
  21. #Region " Imports "
  22.  
  23. Imports System.Collections.Generic
  24. Imports System.Linq
  25. Imports System.Runtime.CompilerServices
  26. Imports System.Windows.Forms
  27.  
  28. #If Not NETCOREAPP Then
  29. Imports DevCase.ProjectMigration
  30. #Else
  31. Imports System.Runtime.Versioning
  32. #End If
  33. #End Region
  34.  
  35. #Region " ToolStrip Extensions "
  36.  
  37. ' ReSharper disable once CheckNamespace
  38.  
  39. Namespace DevCase.Extensions.ToolStripExtensions
  40.  
  41. ''' ----------------------------------------------------------------------------------------------------
  42. ''' <summary>
  43. ''' Provides custom extension methods to use with <see cref="System.Windows.Forms.ToolStrip"/> class.
  44. ''' </summary>
  45. ''' ----------------------------------------------------------------------------------------------------
  46. <HideModuleName>
  47. Public Module ToolStripExtensions
  48.  
  49. #Region " Public Extension Methods "
  50.  
  51. ''' ---------------------------------------------------------------------------------------------------
  52. ''' <summary>
  53. ''' Iterates through all the items of the specified type within the source <see cref="ToolStrip"/> control,
  54. ''' optionally recursively, and performs the specified action on each item.
  55. ''' </summary>
  56. ''' ---------------------------------------------------------------------------------------------------
  57. ''' <param name="toolStrip">
  58. ''' The <see cref="ToolStrip"/> control whose items are to be iterated.
  59. ''' </param>
  60. '''
  61. ''' <param name="recursive">
  62. ''' <see langword="True"/> to iterate recursively through all items
  63. ''' (i.e., iterate the child items of child items); otherwise, <see langword="False"/>.
  64. ''' </param>
  65. '''
  66. ''' <param name="action">
  67. ''' The action to perform on each item.
  68. ''' </param>
  69. ''' ---------------------------------------------------------------------------------------------------
  70. <Extension>
  71. <DebuggerStepThrough>
  72. <EditorBrowsable(EditorBrowsableState.Always)>
  73. Public Sub ForEachItem(toolStrip As ToolStrip, recursive As Boolean, action As Action(Of ToolStripItem))
  74.    ToolStripExtensions.ForEachItem(Of ToolStripItem)(toolStrip, recursive, action)
  75. End Sub
  76.  
  77. ''' ---------------------------------------------------------------------------------------------------
  78. ''' <summary>
  79. ''' Iterates through all the items of the specified type within the source <see cref="ToolStrip"/> control,
  80. ''' optionally recursively, and performs the specified action on each item.
  81. ''' </summary>
  82. ''' ---------------------------------------------------------------------------------------------------
  83. ''' <typeparam name="T">
  84. ''' The type of items to iterate through.
  85. ''' </typeparam>
  86. '''
  87. ''' <param name="toolStrip">
  88. ''' The <see cref="ToolStrip"/> control whose items are to be iterated.
  89. ''' </param>
  90. '''
  91. ''' <param name="recursive">
  92. ''' <see langword="True"/> to iterate recursively through all items
  93. ''' (i.e., iterate the child items of child items); otherwise, <see langword="False"/>.
  94. ''' </param>
  95. '''
  96. ''' <param name="action">
  97. ''' The action to perform on each item.
  98. ''' </param>
  99. ''' ---------------------------------------------------------------------------------------------------
  100. <Extension>
  101. <DebuggerStepThrough>
  102. <EditorBrowsable(EditorBrowsableState.Always)>
  103. Public Sub ForEachItem(Of T As ToolStripItem)(toolStrip As ToolStrip, recursive As Boolean, action As Action(Of T))
  104.    If action Is Nothing Then
  105.        Throw New ArgumentNullException(paramName:=NameOf(action), "Action cannot be null.")
  106.    End If
  107.  
  108.    Dim queue As New Queue(Of ToolStripItem)
  109.  
  110.    ' First level items iteration.
  111.    For Each item As ToolStripItem In toolStrip.Items
  112.        If recursive Then
  113.            queue.Enqueue(item)
  114.        Else
  115.            If TypeOf item Is T Then
  116.                action.Invoke(DirectCast(item, T))
  117.            End If
  118.        End If
  119.    Next item
  120.  
  121.    ' Recursive items iteration.
  122.    While queue.Any()
  123.        Dim currentItem As ToolStripItem = queue.Dequeue()
  124.        If TypeOf currentItem Is T Then
  125.            action.Invoke(DirectCast(currentItem, T))
  126.        End If
  127.  
  128.        If TypeOf currentItem Is ToolStripDropDownItem Then
  129.            Dim dropDownItem As ToolStripDropDownItem = DirectCast(currentItem, ToolStripDropDownItem)
  130.            For Each subItem As ToolStripItem In dropDownItem.DropDownItems
  131.                queue.Enqueue(subItem)
  132.            Next subItem
  133.        End If
  134.    End While
  135. End Sub
  136.  
  137. #End Region
  138.  
  139. End Module
  140.  
  141. End Namespace
  142.  
  143. #End Region



Otros dos métodos para iterar los controles hijo de un control padre (el control padre puede ser de tipo Form, ContainerControl, Control, etc), opcionalmente de forma recursiva (sin recursión de método), y poder llevar a cabo una acción específica sobre cada control:

Código
  1. <HideModuleName>
  2. public module ControlExtensions
  3.  
  4.    ''' ---------------------------------------------------------------------------------------------------
  5.    ''' <summary>
  6.    ''' Iterates through all controls within a parent <see cref="Control"/>,
  7.    ''' optionally recursively, and performs the specified action on each control.
  8.    ''' </summary>
  9.    ''' ---------------------------------------------------------------------------------------------------
  10.    ''' <param name="parentControl">
  11.    ''' The parent <see cref="Control"/> whose child controls are to be iterated.
  12.    ''' </param>
  13.    '''
  14.    ''' <param name="recursive">
  15.    ''' <see langword="True"/> to iterate recursively through all child controls
  16.    ''' (i.e., iterate the child controls of child controls); otherwise, <see langword="False"/>.
  17.    ''' </param>
  18.    '''
  19.    ''' <param name="action">
  20.    ''' The action to perform on each control.
  21.    ''' </param>
  22.    ''' ---------------------------------------------------------------------------------------------------
  23.    <DebuggerStepThrough>
  24.    <Extension>
  25.    <EditorBrowsable(EditorBrowsableState.Always)>
  26.    Public Sub ForEachControl(parentControl As Control, recursive As Boolean, action As Action(Of Control))
  27.        ControlExtensions.ForEachControl(Of Control)(parentControl, recursive, action)
  28.    End Sub
  29.  
  30.    ''' ---------------------------------------------------------------------------------------------------
  31.    ''' <summary>
  32.    ''' Iterates through all controls of the specified type within a parent <see cref="Control"/>,
  33.    ''' optionally recursively, and performs the specified action on each control.
  34.    ''' </summary>
  35.    ''' ---------------------------------------------------------------------------------------------------
  36.    ''' <typeparam name="T">
  37.    ''' The type of child controls to iterate through.
  38.    ''' </typeparam>
  39.    '''
  40.    ''' <param name="parentControl">
  41.    ''' The parent <see cref="Control"/> whose child controls are to be iterated.
  42.    ''' </param>
  43.    '''
  44.    ''' <param name="recursive">
  45.    ''' <see langword="True"/> to iterate recursively through all child controls
  46.    ''' (i.e., iterate the child controls of child controls); otherwise, <see langword="False"/>.
  47.    ''' </param>
  48.    '''
  49.    ''' <param name="action">
  50.    ''' The action to perform on each control.
  51.    ''' </param>
  52.    ''' ---------------------------------------------------------------------------------------------------
  53.    <DebuggerStepThrough>
  54.    <Extension>
  55.    <EditorBrowsable(EditorBrowsableState.Always)>
  56.    Public Sub ForEachControl(Of T As Control)(parentControl As Control, recursive As Boolean, action As Action(Of T))
  57.  
  58.        If TypeOf parentControl Is ToolStrip Then
  59.            Throw New InvalidOperationException($"Not allowed. Please use method {NameOf(ToolStripExtensions.ForEachItem)} to iterate items of a {NameOf(ToolStrip)}, {NameOf(StatusStrip)}, {NameOf(MenuStrip)} or {NameOf(Control.ContextMenuStrip)} controls.")
  60.        End If
  61.  
  62.        If action Is Nothing Then
  63.            Throw New ArgumentNullException(paramName:=NameOf(action), "Action cannot be null.")
  64.        End If
  65.  
  66.        Dim queue As New Queue(Of Control)
  67.  
  68.        ' First level items iteration.
  69.        For Each control As Control In parentControl.Controls
  70.            If recursive Then
  71.                queue.Enqueue(control)
  72.            Else
  73.                If TypeOf control Is T Then
  74.                    action.Invoke(DirectCast(control, T))
  75.                End If
  76.            End If
  77.        Next control
  78.  
  79.        ' Recursive items iteration.
  80.        While queue.Any()
  81.            Dim currentControl As Control = queue.Dequeue()
  82.            If TypeOf currentControl Is T Then
  83.                action.Invoke(DirectCast(currentControl, T))
  84.            End If
  85.  
  86.            For Each childControl As Control In currentControl.Controls
  87.                queue.Enqueue(childControl)
  88.            Next childControl
  89.        End While
  90.  
  91.    End Sub
  92.  
  93. end module
« Última modificación: 12 Abril 2024, 05:09 am por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #584 en: 15 Abril 2024, 12:40 pm »

El siguiente método sirve para aplicar, de forma automatizada, y recursivamente, los recursos aplicables de localización para un Form específico, o para todos los Forms visibles de la aplicación actual.

En otras palabras, el siguiente método sirve para automatizar un cambio de idioma en nuestra aplicación, y tan solo necesitando una línea de código para llamar a dicho método...



He tenido que desarrollar este método, por que todas las alternativas que hay disponibles por Internet son muy básicas e ineficientes, ya que se limitan a iterar los controles y controles hijo, mientras que mi implementación además también itera los menús y sus items de forma recursiva, y los componentes de un form (como un NotifyIcon).



Ejemplos de uso:

Código
  1. ' Aplica recursos de localización a un form específico
  2. Dim form As Form = Me
  3. Dim cultureName As String = "es-ES"
  4. ApplyCultureResources(form, cultureName)

Código
  1. ' Aplica recursos de localización a todos los forms de la aplicación
  2. Dim cultureName As String = "es-ES"
  3. ApplyCultureResources(cultureName)

Salida de depuración (ejemplo limitado):

Cambio de idioma a Inglés:
Código:
Culture: English (en), Component: Form1                 , Text: My Form
Culture: English (en), Component: Button1               , Text: My Button
Culture: English (en), Component: ToolStrip1            , Text: (null)
Culture: English (en), Component: ToolStripStatusLabel1 , Text: Testing
Culture: English (en), Component: MenuStrip1            , Text: (null)
Culture: English (en), Component: ToolStripMenuItem1    , Text: One
Culture: English (en), Component: ToolStripMenuItem2    , Text: Two
Culture: English (en), Component: TabControl1           , Text: (null)
Culture: English (en), Component: TabPage1              , Text: Page 1
Culture: English (en), Component: TabPage2              , Text: Page 2
Culture: English (en), Component: NotifyIcon1           , Text: Icon

Cambio de idioma a Español:
Código:
Culture: Spanish (es), Component: Form1                 , Text: Mi Form
Culture: Spanish (es), Component: Button1               , Text: Mi Botón
Culture: Spanish (es), Component: ToolStrip1            , Text: (null)
Culture: Spanish (es), Component: ToolStripStatusLabel1 , Text: Probando
Culture: Spanish (es), Component: MenuStrip1            , Text: (null)
Culture: Spanish (es), Component: ToolStripMenuItem1    , Text: Uno
Culture: Spanish (es), Component: ToolStripMenuItem2    , Text: Dos
Culture: Spanish (es), Component: TabControl1           , Text: (null)
Culture: Spanish (es), Component: TabPage1              , Text: Página 1
Culture: Spanish (es), Component: TabPage2              , Text: Página 2
Culture: Spanish (es), Component: NotifyIcon1           , Text: Icono



IMPORTANTE: el siguiente método depende de los métodos de extensión ForEachControl y ForEachItem que compartí en el post anterior de este hilo:


Y también depende de este otro método de extensión:

Código
  1. ''' <summary>
  2. ''' Provides extension methods for the <see cref="WinForms.IContainerControl"/> interface.
  3. ''' </summary>
  4. <HideModuleName>
  5. Public Module IContainerControlExtensions
  6.  
  7.  
  8.    ''' <summary>
  9.    ''' Gets the underlying <see cref="System.ComponentModel.ComponentCollection"/> collection
  10.    ''' of the source <see cref="IContainerControl"/>.
  11.    ''' </summary>
  12.    '''
  13.    ''' <param name="container">
  14.    ''' The source <see cref="IContainerControl"/>.
  15.    ''' </param>
  16.    '''
  17.    ''' <returns>
  18.    ''' The underlying <see cref="System.ComponentModel.ComponentCollection"/> collection
  19.    ''' of the source <see cref="IContainerControl"/>.
  20.    ''' </returns>
  21.    <DebuggerStepThrough>
  22.    <Extension>
  23.    <EditorBrowsable(EditorBrowsableState.Always)>
  24.    Public Function GetComponentCollection(container As IContainerControl) As ComponentCollection
  25.        Dim type As Type = container.GetType()
  26.        Dim componentsField As FieldInfo = type.GetField("components", BindingFlags.NonPublic Or BindingFlags.Instance)
  27.  
  28.        If componentsField Is Nothing Then
  29.            Throw New InvalidOperationException("""components"" field was not found through Reflection.")
  30.        End If
  31.  
  32.        Dim containerComponents As IContainer = TryCast(componentsField.GetValue(container), IContainer)
  33.        Return containerComponents?.Components
  34.    End Function
  35.  
  36. End Module



El código:

Código
  1. ''' <summary>
  2. ''' This method sets the current UI culture to the specified culture name,
  3. ''' then applies culture-specific resources to the specified <see cref="Form"/>,
  4. ''' to its controls and child controls, including menus and their items, and
  5. ''' the components in the form's <see cref="ComponentCollection"/>, recursively.
  6. ''' </summary>
  7. '''
  8. ''' <example> This is a code example.
  9. ''' <code language="VB">
  10. ''' Dim form As Form = Me
  11. ''' Dim cultureName As String = "es-ES"
  12. ''' ApplyCultureResources(form, cultureName)
  13. ''' </code>
  14. ''' </example>
  15. '''
  16. ''' <param name="form">
  17. ''' The form to apply resources to.
  18. ''' </param>
  19. '''
  20. ''' <param name="cultureName">
  21. ''' The culture name of the resources to apply.
  22. ''' </param>
  23. Public Shared Sub ApplyCultureResources(form As Form, cultureName As String)
  24.  
  25.    Dim culture As CultureInfo = CultureInfo.GetCultureInfo(cultureName)
  26. #If Not NETCOREAPP Then
  27.            My.Application.ChangeUICulture(cultureName)
  28. #Else
  29.            Thread.CurrentThread.CurrentUICulture = culture
  30. #End If
  31.  
  32.    Dim resources As New ComponentResourceManager(form.GetType())
  33.  
  34.    ' Action delegate that applies resources to an IComponent.
  35.    Dim applyResources As Action(Of IComponent, String) =
  36.        Sub(component As IComponent, name As String)
  37.            If String.IsNullOrEmpty(name) Then
  38.                ' Not valid to apply localization resources.
  39.                Exit Sub
  40.            Else
  41.                resources.ApplyResources(component, name, culture)
  42.            End If
  43.  
  44.            ' Applies resources to the items and subitems of a ToolStrip component, recursively.
  45.            If TypeOf component Is ToolStrip Then
  46.                Dim ts As ToolStrip = DirectCast(component, ToolStrip)
  47.                ToolStripExtensions.ForEachItem(ts, recursive:=True, Sub(item) applyResources(item, item.Name))
  48.            End If
  49.  
  50. #If DEBUG Then ' Prints debug information.
  51.            ' Flags to retrieve the "Text" property of a component.
  52.            Const textPropBindingFlags As BindingFlags =
  53.                BindingFlags.Instance Or BindingFlags.Static Or
  54.                BindingFlags.Public Or BindingFlags.NonPublic
  55.  
  56.            Dim textProp As PropertyInfo =
  57.                (From prop As PropertyInfo In component.GetType().GetProperties(textPropBindingFlags)
  58.                 Where prop.PropertyType Is GetType(String) AndAlso
  59.                       prop.Name.Equals("Text", StringComparison.OrdinalIgnoreCase)
  60.                ).SingleOrDefault()
  61.  
  62.            Dim text As String = DirectCast(textProp?.GetValue(component), String)
  63.            If String.IsNullOrEmpty(text) Then
  64.                text = "(null)"
  65.            End If
  66.            Debug.WriteLine($"Culture: {culture.EnglishName} ({culture.Name}), Component: {name,-40}, Text: {text}")
  67. #End If
  68.        End Sub
  69.  
  70.    ' Apply resources to the form.
  71.    applyResources(form, form.Name)
  72.  
  73.    ' Apply resources to the controls hosted in the form, recursively.
  74.    FormExtensions.ForEachControl(form, recursive:=True, Sub(ctrl) applyResources(ctrl, ctrl.Name))
  75.  
  76.    ' Apply resources to the components hosted in the ComponentCollection of the form.
  77.    Dim components As ComponentCollection = IContainerControlExtensions.GetComponentCollection(form)
  78.    If components IsNot Nothing Then
  79.        ' Flags to retrieve the "Name" property of a component.
  80.        Const namePropBindingFlags As BindingFlags =
  81.            BindingFlags.Instance Or BindingFlags.Static Or
  82.            BindingFlags.Public Or BindingFlags.NonPublic
  83.  
  84.        For Each component As IComponent In components
  85.            Dim nameProp As PropertyInfo =
  86.                  (From prop As PropertyInfo In component.GetType().GetProperties(namePropBindingFlags)
  87.                   Where prop.PropertyType Is GetType(String) AndAlso
  88.                         prop.Name.Equals("Name", StringComparison.OrdinalIgnoreCase)
  89.                  ).SingleOrDefault()
  90.  
  91.            Dim name As String = DirectCast(nameProp?.GetValue(component), String)
  92.            applyResources(component, name)
  93.        Next component
  94.    End If
  95.  
  96.    ' This code finds and applies resources to component fields declared at the form level
  97.    ' (including those in the auto-generated code of the form designer) that doesn't have
  98.    ' defined a "Name" property (such as NotifyIcon, ColorDialog, OpenFileDialog, etc).
  99.    Const fieldsBindingFlags As BindingFlags =
  100.        BindingFlags.Instance Or BindingFlags.DeclaredOnly Or BindingFlags.Static Or
  101.        BindingFlags.Public Or BindingFlags.NonPublic
  102.  
  103.    Dim fields As IEnumerable(Of FieldInfo) =
  104.                From field As FieldInfo In form.GetType().GetFields(fieldsBindingFlags)
  105.                Where GetType(IComponent).IsAssignableFrom(field.FieldType) AndAlso
  106.                  Not GetType(Control).IsAssignableFrom(field.FieldType) AndAlso
  107.                  Not GetType(ToolStripItem).IsAssignableFrom(field.FieldType)
  108.  
  109.    For Each field As FieldInfo In fields
  110.        Dim component As IComponent = DirectCast(field.GetValue(form), IComponent)
  111.        Dim name As String = field.Name.TrimStart("_"c) ' E.g.: "_NotifyIcon1" -> "NotifyIcon1"
  112.        applyResources(component, name)
  113.    Next field
  114.  
  115. End Sub

Código
  1. ''' <summary>
  2. ''' This method sets the current UI culture to the specified culture name,
  3. ''' then applies culture-specific resources to the open forms of the current application,
  4. ''' to its controls and child controls, including menus and their items, and
  5. ''' the components in the form's <see cref="ComponentCollection"/>, recursively.
  6. ''' </summary>
  7. '''
  8. ''' <example> This is a code example.
  9. ''' <code language="VB">
  10. ''' Dim cultureName As String = "es-ES"
  11. ''' ApplyCultureResources(cultureName)
  12. ''' </code>
  13. ''' </example>
  14. '''
  15. ''' <param name="cultureName">
  16. ''' The culture name of the resources to apply.
  17. ''' </param>
  18. Public Shared Sub ApplyCultureResources(cultureName As String)
  19.    For Each form As Form In System.Windows.Forms.Application.OpenForms
  20.        ApplyCultureResources(form, cultureName)
  21.    Next form
  22. End Sub
« Última modificación: 15 Abril 2024, 14:42 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

Dos métodos de extensión que nos permiten, de forma simple y sencilla usado solamente una línea de código, desactivar o activar una o varias pestañas de un TabControl, lo que no se limita solamente a desactivar la página (propiedad: TabPage.Enabled), sino también a prohibir o permitir que las pestañas puedan seleccionarse en el TabControl.

Modo de empleo:

Para desactivar una o varias pestañas:
Código
  1. TabControl1.DisableTabs(TabPage1, TabPage2)

Para (re)activar una o varias pestañas:
Código
  1. TabControl1.EnableTabs(TabPage1, TabPage2)

El Código:

Código
  1. Imports System.Runtime.CompilerServices
  2.  
  3. ''' <summary>
  4. ''' Provides extension methods for a <see cref="TabControl"/> control.
  5. ''' </summary>
  6. <HideModuleName>
  7. Public Module TabControlExtensions
  8.  
  9.    ''' <summary>
  10.    ''' Collection used to store tab pages whose tab header need to remain disabled on a <see cref="TabControl"/>.
  11.    ''' <para></para>
  12.    ''' This collection depends on <see cref="TabControlExtensions.DisableOrEnableTabs_Internal"/> method.
  13.    ''' </summary>
  14.    Private disabledTabs As HashSet(Of TabPage)
  15.  
  16.    ''' <summary>
  17.    ''' Collection used to store tab controls whose its <see cref="TabControl.Selecting"/> event
  18.    ''' has been associated to <see cref="TabControlExtensions.disableTabPageHandler"/>.
  19.    ''' <para></para>
  20.    ''' This collection depends on <see cref="TabControlExtensions.DisableOrEnableTabs_Internal"/> method.
  21.    ''' </summary>
  22.    Private tabHandlerAddedControls As HashSet(Of TabControl)
  23.  
  24.    ''' <summary>
  25.    ''' A <see cref="TabControlCancelEventHandler"/> delegate used for disabling tabs on a <see cref="TabControl"/>.
  26.    ''' <para></para>
  27.    ''' This handler depends on <see cref="TabControlExtensions.DisableOrEnableTabs_Internal"/> method.
  28.    ''' </summary>
  29.    Private tabDisablerHandler As TabControlCancelEventHandler
  30.  
  31.    ''' <summary>
  32.    ''' Disables one or multiple <see cref="TabPage"/>,
  33.    ''' making the tabs unselectable in the source <see cref="TabControl"/>.
  34.    ''' </summary>
  35.    '''
  36.    ''' <param name="tabControl">
  37.    ''' The source <see cref="TabControl"/>.
  38.    ''' </param>
  39.    '''
  40.    ''' <param name="tabPages">
  41.    ''' An Array of <see cref="TabPage"/> to disable.
  42.    ''' </param>
  43.    <Extension>
  44.    <DebuggerStepThrough>
  45.    Public Sub DisableTabs(tabControl As TabControl, ParamArray tabPages As TabPage())
  46.        TabControlExtensions.DisableOrEnableTabs_Internal(tabControl, enabled:=False, tabPages)
  47.    End Sub
  48.  
  49.    ''' <summary>
  50.    ''' Enables one or multiple <see cref="TabPage"/> that were previously
  51.    ''' disabled by a call to <see cref="TabControlExtensions.DisableTabPages"/> method,
  52.    ''' making the tabs selectable again in the source <see cref="TabControl"/>.
  53.    ''' </summary>
  54.    '''
  55.    ''' <param name="tabControl">
  56.    ''' The source <see cref="TabControl"/>.
  57.    ''' </param>
  58.    '''
  59.    ''' <param name="tabPages">
  60.    ''' An Array of <see cref="TabPage"/> to enable.
  61.    ''' </param>
  62.    <Extension>
  63.    <DebuggerStepThrough>
  64.    Public Sub EnableTabs(tabControl As TabControl, ParamArray tabPages As TabPage())
  65.        TabControlExtensions.DisableOrEnableTabs_Internal(tabControl, enabled:=True, tabPages)
  66.    End Sub
  67.  
  68.    ''' <summary>
  69.    ''' *** FOR INTERNAL USE ONLY ***
  70.    ''' <para></para>
  71.    ''' Disables or enables one or multiple <see cref="TabPage"/>,
  72.    ''' denying or allowing their tab selection in the source <see cref="TabControl"/>.
  73.    ''' </summary>
  74.    '''
  75.    ''' <param name="tabControl">
  76.    ''' The source <see cref="TabControl"/>.
  77.    ''' </param>
  78.    '''
  79.    ''' <param name="enabled">
  80.    ''' If <see langword="False"/>, disables the tab pages and make them unselectable in the source <see cref="TabControl"/>;
  81.    ''' otherwise, enable the tab pages and allows to be selected in the source <see cref="TabControl"/>.
  82.    ''' </param>
  83.    '''
  84.    ''' <param name="tabPages">
  85.    ''' An Array of the tab pages to disable or enable.
  86.    ''' </param>
  87.    <DebuggerStepThrough>
  88.    Private Sub DisableOrEnableTabs_Internal(tabControl As TabControl, enabled As Boolean, ParamArray tabPages As TabPage())
  89.        If tabControl Is Nothing Then
  90.            Throw New ArgumentNullException(paramName:=NameOf(tabControl))
  91.        End If
  92.        If tabPages Is Nothing Then
  93.            Throw New ArgumentNullException(paramName:=NameOf(tabPages))
  94.        End If
  95.  
  96.        ' Initialize collections.
  97.        If TabControlExtensions.disabledTabs Is Nothing Then
  98.            TabControlExtensions.disabledTabs = New HashSet(Of TabPage)
  99.        End If
  100.        If TabControlExtensions.tabHandlerAddedControls Is Nothing Then
  101.            TabControlExtensions.tabHandlerAddedControls = New HashSet(Of TabControl)
  102.        End If
  103.  
  104.        ' Initialize handler.
  105.        If TabControlExtensions.tabDisablerHandler Is Nothing Then
  106.            TabControlExtensions.tabDisablerHandler =
  107.                Sub(sender As Object, e As TabControlCancelEventArgs)
  108.                    If e.TabPageIndex < 0 Then
  109.                        Exit Sub
  110.                    End If
  111.  
  112.                    Select Case e.Action
  113.                        Case TabControlAction.Selecting, TabControlAction.Selected
  114.                            e.Cancel = TabControlExtensions.disabledTabs.Contains(e.TabPage)
  115.                        Case Else
  116.                            Exit Sub
  117.                    End Select
  118.                End Sub
  119.        End If
  120.  
  121.        For Each tabPage As TabPage In tabPages
  122.            If tabPage Is Nothing Then
  123.                Throw New NullReferenceException($"{NameOf(tabPage)} object is null.")
  124.            End If
  125.  
  126.            ' Disable or enable the tab page.
  127.            tabPage.Enabled = enabled
  128.  
  129.            If Not enabled Then ' Disable the tab header.
  130.                Dim success As Boolean = disabledTabs.Add(tabPage)
  131.                If success AndAlso Not TabControlExtensions.tabHandlerAddedControls.Contains(tabControl) Then
  132.                    AddHandler tabControl.Selecting, TabControlExtensions.tabDisablerHandler
  133.                    TabControlExtensions.tabHandlerAddedControls.Add(tabControl)
  134.                End If
  135.            Else ' Enable the tab header.
  136.                Dim success As Boolean = disabledTabs.Remove(tabPage)
  137.                If success AndAlso TabControlExtensions.tabHandlerAddedControls.Contains(tabControl) AndAlso
  138.                               Not TabControlExtensions.disabledTabs.Any() Then
  139.                    RemoveHandler tabControl.Selecting, TabControlExtensions.tabDisablerHandler
  140.                    TabControlExtensions.tabHandlerAddedControls.Remove(tabControl)
  141.                End If
  142.            End If
  143.        Next tabPage
  144.  
  145.    End Sub
  146.  
  147. End Module
« Última modificación: 16 Abril 2024, 12:26 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #586 en: 16 Abril 2024, 12:24 pm »

Un método de extensión para impedir que un ToolStripMenuItem se cierre al hacer click en uno de sus items hijos.

Ejemplo de uso:

Código
  1. Dim menuItem As ToolStripMenuItem = Me.ToolStripMenuItem1
  2. Dim preventClosure As Boolean = True
  3. Dim recursive As Boolean = False
  4. menuItem.SetClosureBehaviorOnClick(preventClosure, recursive)



El código:

Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 12-April-2024
  4. ' ***********************************************************************
  5.  
  6. #Region " Public Members Summary "
  7.  
  8. ' ToolStripMenuItem.SetClosureBehaviorOnClick(Boolean, Boolean)
  9.  
  10. #End Region
  11.  
  12. #Region " Option Statements "
  13.  
  14. Option Strict On
  15. Option Explicit On
  16. Option Infer Off
  17.  
  18. #End Region
  19.  
  20. #Region " Imports "
  21.  
  22. Imports System.Collections.Generic
  23. Imports System.ComponentModel
  24. Imports System.Linq
  25. Imports System.Runtime.CompilerServices
  26. Imports System.Windows.Forms
  27.  
  28. #End Region
  29.  
  30. #Region " ToolStripMenuItem Extensions "
  31.  
  32. Namespace DevCase.Core.Extensions
  33.  
  34.    ''' ----------------------------------------------------------------------------------------------------
  35.    ''' <summary>
  36.    ''' Provides extension methods to use with the <see cref="ToolStripMenuItem"/> class.
  37.    ''' </summary>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    <HideModuleName>
  40.    Public Module ToolStripMenuItemExtensions
  41.  
  42. #Region " Public Extension Methods "
  43.  
  44.        ''' <summary>
  45.        ''' A <see cref="ToolStripDropDownClosingEventHandler"/> delegate used to control
  46.        ''' the <see cref="ToolStripDropDown.Closing"/> event of a <see cref="ToolStripDropDown"/>.
  47.        ''' <para></para>
  48.        ''' This handler depends on <see cref="ToolStripMenuItemExtensions.SetClosureBehaviorOnClick"/> method.
  49.        ''' </summary>
  50.        Private closingHandler As ToolStripDropDownClosingEventHandler
  51.  
  52.        ''' <summary>
  53.        ''' A collection of <see cref="ToolStripDropDown"/> items
  54.        ''' whose <see cref="ToolStripDropDown.Closing"/> event
  55.        ''' has been associated to <see cref="ToolStripMenuItemExtensions.closingHandler"/>.
  56.        ''' <para></para>
  57.        ''' This collection depends on <see cref="ToolStripMenuItemExtensions.SetClosureBehaviorOnClick"/> method.
  58.        ''' </summary>
  59.        Private closingHandlerAssociatedItems As HashSet(Of ToolStripDropDown)
  60.  
  61.        ''' <summary>
  62.        ''' Sets the closure behavior for the source <see cref="ToolStripMenuItem"/> when its drop-down items are clicked.
  63.        ''' </summary>
  64.        '''
  65.        ''' <remarks>
  66.        ''' This method associates the underlying
  67.        ''' <see cref="ToolStripMenuItem.DropDown"/>'s <see cref="ToolStripDropDown.Closing"/> event
  68.        ''' with a handler to control the closure behavior.
  69.        ''' </remarks>
  70.        '''
  71.        ''' <example> This is a code example.
  72.        ''' <code language="VB">
  73.        ''' Dim menuItem As ToolStripMenuItem = Me.ToolStripMenuItem1
  74.        ''' Dim preventClosure As Boolean = True
  75.        ''' Dim recursive As Boolean = True
  76.        '''
  77.        ''' menuItem.SetClosureBehaviorOnClick(preventClosure, recursive)
  78.        ''' </code>
  79.        ''' </example>
  80.        '''
  81.        ''' <param name="menuItem">
  82.        ''' The <see cref="ToolStripMenuItem"/> to set the closure behavior for.
  83.        ''' </param>
  84.        '''
  85.        ''' <param name="preventClosure">
  86.        ''' <see langword="True"/> to prevent closure of the source <see cref="ToolStripMenuItem"/>
  87.        ''' when its drop-down items are clicked; otherwise, <see langword="False"/>.
  88.        ''' </param>
  89.        <DebuggerStepThrough>
  90.        <Extension>
  91.        <EditorBrowsable(EditorBrowsableState.Always)>
  92.        Public Sub SetClosureBehaviorOnClick(menuItem As ToolStripMenuItem, preventClosure As Boolean, recursive As Boolean)
  93.            If menuItem Is Nothing Then
  94.                Throw New ArgumentNullException(paramName:=NameOf(menuItem))
  95.            End If
  96.  
  97.            If Not menuItem.HasDropDown Then
  98.                Throw New InvalidOperationException(
  99.                "The ToolStripDropDownItem.DropDown for the ToolStripDropDownItem has not been created.")
  100.            End If
  101.  
  102.            If ToolStripMenuItemExtensions.closingHandler Is Nothing Then
  103.                ToolStripMenuItemExtensions.closingHandler =
  104.                    Sub(sender As Object, e As ToolStripDropDownClosingEventArgs)
  105.                        e.Cancel = (e.CloseReason = ToolStripDropDownCloseReason.ItemClicked)
  106.                    End Sub
  107.            End If
  108.  
  109.            If ToolStripMenuItemExtensions.closingHandlerAssociatedItems Is Nothing Then
  110.                ToolStripMenuItemExtensions.closingHandlerAssociatedItems = New HashSet(Of ToolStripDropDown)
  111.            End If
  112.  
  113.            Dim dropdownAction As Action(Of ToolStripDropDown) =
  114.                Sub(dropdown As ToolStripDropDown)
  115.                    If preventClosure Then
  116.                        If Not ToolStripMenuItemExtensions.closingHandlerAssociatedItems.Contains(dropdown) Then
  117.                            AddHandler dropdown.Closing, ToolStripMenuItemExtensions.closingHandler
  118.                            ToolStripMenuItemExtensions.closingHandlerAssociatedItems.Add(dropdown)
  119.                        End If
  120.                    Else
  121.                        If ToolStripMenuItemExtensions.closingHandlerAssociatedItems.Contains(dropdown) Then
  122.                            RemoveHandler dropdown.Closing, ToolStripMenuItemExtensions.closingHandler
  123.                            ToolStripMenuItemExtensions.closingHandlerAssociatedItems.Remove(dropdown)
  124.                        End If
  125.                    End If
  126.                End Sub
  127.  
  128.            Dim queue As New Queue(Of ToolStripDropDown)
  129.  
  130.            ' Root level items iteration.
  131.            If recursive Then
  132.                queue.Enqueue(menuItem.DropDown)
  133.            Else
  134.                If TypeOf menuItem Is ToolStripMenuItem Then
  135.                    dropdownAction(menuItem.DropDown)
  136.                End If
  137.            End If
  138.  
  139.            ' Recursive items iteration.
  140.            While queue.Any()
  141.                Dim currentItem As ToolStripDropDown = queue.Dequeue()
  142.                dropdownAction(currentItem)
  143.  
  144.                If currentItem.HasChildren Then
  145.                    For Each subMenuItem As ToolStripMenuItem In currentItem.Items.OfType(Of ToolStripMenuItem)
  146.                        If subMenuItem.HasDropDown Then
  147.                            queue.Enqueue(subMenuItem.DropDown)
  148.                        End If
  149.                    Next
  150.                End If
  151.            End While
  152.        End Sub
  153.  
  154. #End Region
  155.  
  156.    End Module
  157.  
  158. End Namespace
  159.  
  160. #End Region
  161.  
« Última modificación: 16 Abril 2024, 13:43 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

En esta ocasión comparto el código fuente de un control de tipo NumericUpDown para poder usarlo en una barra ToolStrip o StatusStrip, y también un control de tipo TrackBar con la misma finalidad.





ToolStripNumericUpDown.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 19-April-2024
  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 " Imports "
  15.  
  16. Imports System.ComponentModel
  17. Imports System.Drawing
  18. Imports System.Runtime.InteropServices
  19. Imports System.Windows.Forms
  20. Imports System.Windows.Forms.Design
  21.  
  22. #End Region
  23.  
  24. #Region " ToolStripNumericUpDown "
  25.  
  26. ' ReSharper disable once CheckNamespace
  27.  
  28. Namespace DevCase.UI.Components
  29.  
  30.    ''' <summary>
  31.    ''' Represents a selectable Windows spin box <see cref="ToolStripItem"/> that displays numeric values.
  32.    ''' </summary>
  33.    ''' <seealso cref="ToolStripControlHost"/>
  34.    <
  35.        ComVisible(True),
  36.        DebuggerStepThrough,
  37.        DefaultEvent(NameOf(ToolStripNumericUpDown.ValueChanged)),
  38.        DefaultProperty(NameOf(ToolStripNumericUpDown.Value)),
  39.        DefaultBindingProperty(NameOf(ToolStripNumericUpDown.Value)),
  40.        Description("Represents a selectable Windows spin box ToolStripItem that displays numeric values."),
  41.        Designer("System.Windows.Forms.Design.ToolStripItemDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
  42.        DesignerCategory(NameOf(DesignerCategoryAttribute.Generic)),
  43.        DesignTimeVisible(False),
  44.        DisplayName(NameOf(ToolStripNumericUpDown)),
  45.        Localizable(True),
  46.        ToolboxBitmap(GetType(NumericUpDown), "NumericUpDown.bmp"),
  47.        ToolboxItem(False),
  48.        ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Allow),
  49.        ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip Or ToolStripItemDesignerAvailability.StatusStrip)
  50.    >
  51.    Public Class ToolStripNumericUpDown : Inherits ToolStripControlHost
  52.  
  53. #Region " Properties "
  54.  
  55.        ''' <summary>
  56.        ''' Gets the <see cref="NumericUpDown"/> control that is hosted by this <see cref="ToolStripNumericUpDown"/>.
  57.        ''' </summary>
  58.        <
  59.            Browsable(True), EditorBrowsable(EditorBrowsableState.Advanced),
  60.            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
  61.            Category("Components"), Description("The NumericUpDown control that is hosted by this control.")
  62.        >
  63.        Public Shadows ReadOnly Property Control As NumericUpDown
  64.            Get
  65.                Return DirectCast(MyBase.Control, NumericUpDown)
  66.            End Get
  67.        End Property
  68.  
  69.        ''' <summary>
  70.        ''' Gets or sets the numeric value assigned to this <see cref="ToolStripNumericUpDown"/>.
  71.        ''' </summary>
  72.        '''
  73.        ''' <value>
  74.        ''' The numeric value assigned to this <see cref="ToolStripNumericUpDown"/>.
  75.        ''' </value>
  76.        <
  77.            Bindable(True),
  78.            DefaultValue(0D),
  79.            Category("Appearance"), Description("The numeric value assigned to this control.")
  80.        >
  81.        Public Property Value As Decimal
  82.            Get
  83.                Return Me.Control.Value
  84.            End Get
  85.            Set(value As Decimal)
  86.                Me.Control.Value = value
  87.            End Set
  88.        End Property
  89.  
  90.        ''' <summary>
  91.        ''' Gets or sets the text to be displayed in this <see cref="ToolStripNumericUpDown"/>.
  92.        ''' </summary>
  93.        '''
  94.        ''' <value>
  95.        ''' The text to be displayed in this <see cref="ToolStripNumericUpDown"/>.
  96.        ''' </value>
  97.        <
  98.            Browsable(False), EditorBrowsable(EditorBrowsableState.Never),
  99.            Bindable(False),
  100.            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
  101.            Category("Behavior"), Description("The text to be displayed in this control.")
  102.        >
  103.        Public Overrides Property Text As String
  104.            Get
  105.                Return Me.Control.Text
  106.            End Get
  107.            Set(value As String)
  108.                Me.Control.Text = value
  109.            End Set
  110.        End Property
  111.  
  112.        ''' <summary>
  113.        ''' This property is not applicable for this control.
  114.        ''' </summary>
  115.        <
  116.            Browsable(False), EditorBrowsable(EditorBrowsableState.Never),
  117.            Category("Not Applicable"), Description("This property is not applicable for this control.")
  118.        >
  119.        Public Overrides Property BackgroundImage As Image
  120.            Get
  121.                Return Nothing
  122.            End Get
  123.            Set(value As Image)
  124.                MyBase.BackgroundImage = Nothing
  125.            End Set
  126.        End Property
  127.  
  128.        ''' <summary>
  129.        ''' This property is not applicable for this control.
  130.        ''' </summary>
  131.        <
  132.            Browsable(False), EditorBrowsable(EditorBrowsableState.Never),
  133.            Category("Not Applicable"), Description("This property is not applicable for this control.")
  134.        >
  135.        Public Overrides Property BackgroundImageLayout As ImageLayout
  136.            Get
  137.                Return MyBase.BackgroundImageLayout
  138.            End Get
  139.            Set(value As ImageLayout)
  140.                MyBase.BackgroundImageLayout = value
  141.            End Set
  142.        End Property
  143.  
  144.        ''' <summary>
  145.        ''' This property is not applicable for this control.
  146.        ''' </summary>
  147.        <
  148.            Browsable(False), EditorBrowsable(EditorBrowsableState.Never),
  149.            Category("Not Applicable"), Description("This property is not applicable for this control.")
  150.        >
  151.        Public Overrides Property Image As Image
  152.            Get
  153.                Return Nothing
  154.            End Get
  155.            Set(value As Image)
  156.                MyBase.Image = Nothing
  157.            End Set
  158.        End Property
  159.  
  160. #End Region
  161.  
  162. #Region " Events "
  163.  
  164.        ''' <summary>
  165.        ''' Occurs whenever the <see cref="ToolStripNumericUpDown.Value"/> property is changed.
  166.        ''' </summary>
  167.        <
  168.            Category("Action"), Description("Occurs whenever the Value property is changed.")
  169.        >
  170.        Public Event ValueChanged As EventHandler
  171.  
  172. #End Region
  173.  
  174. #Region " Constructors "
  175.  
  176.        ''' <summary>
  177.        ''' Initializes a new instance of the <see cref="ToolStripNumericUpDown"/> class.
  178.        ''' </summary>
  179.        Public Sub New()
  180.            MyBase.New(ToolStripNumericUpDown.CreateControlInstance())
  181.        End Sub
  182.  
  183. #End Region
  184.  
  185. #Region " Event Invocators "
  186.  
  187.        ''' <summary>
  188.        ''' Raises the <see cref="ToolStripNumericUpDown.ValueChanged"/> event.
  189.        ''' </summary>
  190.        '''
  191.        ''' <param name="sender">
  192.        ''' The source of the event.
  193.        ''' </param>
  194.        '''
  195.        ''' <param name="e">
  196.        ''' The <see cref="EventArgs"/> instance containing the event data.
  197.        ''' </param>
  198.        Private Sub OnValueChanged(sender As Object, e As EventArgs)
  199.            If Me.ValueChangedEvent IsNot Nothing Then
  200.                RaiseEvent ValueChanged(Me, e)
  201.            End If
  202.        End Sub
  203.  
  204. #End Region
  205.  
  206. #Region " Event Invocators (Overriden) "
  207.  
  208.        ''' <summary>
  209.        ''' Subscribes events from the hosted control
  210.        ''' </summary>
  211.        '''
  212.        ''' <param name="control">
  213.        ''' The control from which to subscribe events.
  214.        ''' </param>
  215.        Protected Overrides Sub OnSubscribeControlEvents(control As Control)
  216.            MyBase.OnSubscribeControlEvents(control)
  217.  
  218.            AddHandler DirectCast(control, NumericUpDown).ValueChanged, AddressOf Me.OnValueChanged
  219.        End Sub
  220.  
  221.        ''' <summary>
  222.        ''' Unsubscribes events from the hosted control
  223.        ''' </summary>
  224.        '''
  225.        ''' <param name="control">
  226.        ''' The control from which to unsubscribe events.
  227.        ''' </param>
  228.        Protected Overrides Sub OnUnsubscribeControlEvents(control As Control)
  229.            MyBase.OnUnsubscribeControlEvents(control)
  230.  
  231.            RemoveHandler DirectCast(control, NumericUpDown).ValueChanged, AddressOf Me.OnValueChanged
  232.        End Sub
  233.  
  234. #End Region
  235.  
  236. #Region " Private Methods "
  237.  
  238.        ''' <summary>
  239.        ''' Creates the control instance.
  240.        ''' </summary>
  241.        '''
  242.        ''' <returns>
  243.        ''' The control.
  244.        ''' </returns>
  245.        Private Shared Function CreateControlInstance() As Control
  246.            Return New NumericUpDown() With {.AutoSize = True}
  247.        End Function
  248.  
  249. #End Region
  250.  
  251.    End Class
  252.  
  253. End Namespace
  254.  
  255. #End Region
  256.  




ToolStripTrackBar.vb
Código
  1. ' ***********************************************************************
  2. ' Author   : ElektroStudios
  3. ' Modified : 19-April-2024
  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 " Imports "
  15.  
  16. Imports System.ComponentModel
  17. Imports System.Drawing
  18. Imports System.Runtime.InteropServices
  19. Imports System.Windows.Forms
  20. Imports System.Windows.Forms.Design
  21.  
  22. #End Region
  23.  
  24. #Region " ToolStripTrackBar "
  25.  
  26. ' ReSharper disable once CheckNamespace
  27.  
  28. Namespace DevCase.UI.Components
  29.  
  30.    ''' <summary>
  31.    ''' Represents a selectable track bar <see cref="ToolStripItem"/>.
  32.    ''' </summary>
  33.    ''' <seealso cref="ToolStripControlHost"/>
  34.    <
  35.        ComVisible(True),
  36.        DebuggerStepThrough,
  37.        DefaultEvent(NameOf(ToolStripTrackBar.Scroll)),
  38.        DefaultProperty(NameOf(ToolStripTrackBar.Value)),
  39.        DefaultBindingProperty(NameOf(ToolStripTrackBar.Value)),
  40.        Description("Represents a selectable track bar ToolStripItem."),
  41.        Designer("System.Windows.Forms.Design.ToolStripItemDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
  42.        DesignerCategory(NameOf(DesignerCategoryAttribute.Generic)),
  43.        DesignTimeVisible(False),
  44.        DisplayName(NameOf(ToolStripTrackBar)),
  45.        Localizable(True),
  46.        ToolboxBitmap(GetType(TrackBar), "TrackBar.bmp"),
  47.        ToolboxItem(False),
  48.        ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Allow),
  49.        ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip Or ToolStripItemDesignerAvailability.StatusStrip)
  50.    >
  51.    Public Class ToolStripTrackBar : Inherits ToolStripControlHost
  52.  
  53. #Region " Properties "
  54.  
  55.        ''' <summary>
  56.        ''' Gets the <see cref="TrackBar"/> control that is hosted by this <see cref="ToolStripTrackBar"/>.
  57.        ''' </summary>
  58.        <
  59.            Browsable(True), EditorBrowsable(EditorBrowsableState.Advanced),
  60.            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
  61.            Category("Components"), Description("The TrackBar control that is hosted by this control.")
  62.        >
  63.        Public Shadows ReadOnly Property Control As TrackBar
  64.            Get
  65.                Return DirectCast(MyBase.Control, TrackBar)
  66.            End Get
  67.        End Property
  68.  
  69.        ''' <summary>
  70.        ''' Gets or sets a numeric value that represents the current position of the scroll box on this <see cref="ToolStripTrackBar"/>.
  71.        ''' </summary>
  72.        '''
  73.        ''' <value>
  74.        ''' The numeric value that represents the current position of the scroll box on this <see cref="ToolStripTrackBar"/>.
  75.        ''' </value>
  76.        <
  77.            Bindable(True),
  78.            DefaultValue(0I),
  79.            Category("Behavior"), Description("The numeric value that represents the current position of the scroll box on this control.")
  80.        >
  81.        Public Property Value As Integer
  82.            Get
  83.                Return Me.Control.Value
  84.            End Get
  85.            Set(value As Integer)
  86.                Me.Control.Value = value
  87.            End Set
  88.        End Property
  89.  
  90.        ''' <summary>
  91.        ''' Gets or sets the lower limit of the range this <see cref="ToolStripTrackBar"/> is working with.
  92.        ''' </summary>
  93.        '''
  94.        ''' <value>
  95.        ''' The minimum value for this <see cref="ToolStripTrackBar"/>. The default is 0.
  96.        ''' </value>
  97.        <
  98.            Bindable(True),
  99.            DefaultValue(0I),
  100.            RefreshProperties(RefreshProperties.All),
  101.            Category("Behavior"), Description("The minimum value for this control.")
  102.        >
  103.        Public Property Minimum As Integer
  104.            Get
  105.                Return Me.Control.Minimum
  106.            End Get
  107.            Set(value As Integer)
  108.                Me.Control.Minimum = value
  109.            End Set
  110.        End Property
  111.  
  112.        ''' <summary>
  113.        ''' Gets or sets the upper limit of the range this <see cref="ToolStripTrackBar"/> is working with.
  114.        ''' </summary>
  115.        '''
  116.        ''' <value>
  117.        ''' The maximum value for this <see cref="ToolStripTrackBar"/>. The default is 10.
  118.        ''' </value>
  119.        <
  120.            Bindable(True),
  121.            DefaultValue(10I),
  122.            RefreshProperties(RefreshProperties.All),
  123.            Category("Behavior"), Description("The maximum value for this control.")
  124.        >
  125.        Public Property Maximum As Integer
  126.            Get
  127.                Return Me.Control.Maximum
  128.            End Get
  129.            Set(value As Integer)
  130.                Me.Control.Maximum = value
  131.            End Set
  132.        End Property
  133.  
  134.        ''' <summary>
  135.        ''' This property is not applicable for this control.
  136.        ''' </summary>
  137.        <
  138.            Browsable(False), EditorBrowsable(EditorBrowsableState.Never),
  139.            Category("Not Applicable"), Description("This property is not applicable for this control.")
  140.        >
  141.        Public Overrides Property BackgroundImage As Image
  142.            Get
  143.                Return Nothing
  144.            End Get
  145.            Set(value As Image)
  146.                MyBase.BackgroundImage = Nothing
  147.            End Set
  148.        End Property
  149.  
  150.        ''' <summary>
  151.        ''' This property is not applicable for this control.
  152.        ''' </summary>
  153.        <
  154.            Browsable(False), EditorBrowsable(EditorBrowsableState.Never),
  155.            Category("Not Applicable"), Description("This property is not applicable for this control.")
  156.        >
  157.        Public Overrides Property BackgroundImageLayout As ImageLayout
  158.            Get
  159.                Return MyBase.BackgroundImageLayout
  160.            End Get
  161.            Set(value As ImageLayout)
  162.                MyBase.BackgroundImageLayout = value
  163.            End Set
  164.        End Property
  165.  
  166.        ''' <summary>
  167.        ''' This property is not applicable for this control.
  168.        ''' </summary>
  169.        <
  170.            Browsable(False), EditorBrowsable(EditorBrowsableState.Never),
  171.            Category("Not Applicable"), Description("This property is not applicable for this control.")
  172.        >
  173.        Public Overrides Property Image As Image
  174.            Get
  175.                Return Nothing
  176.            End Get
  177.            Set(value As Image)
  178.                MyBase.Image = Nothing
  179.            End Set
  180.        End Property
  181.  
  182. #End Region
  183.  
  184. #Region " Events "
  185.  
  186.        ''' <summary>
  187.        ''' Occurs when either a mouse or keyboard action moves the scroll box.
  188.        ''' </summary>
  189.        <
  190.            Category("Behavior"), Description("Occurs when either a mouse or keyboard action moves the scroll box.")
  191.        >
  192.        Public Event Scroll As EventHandler
  193.  
  194.        ''' <summary>
  195.        ''' Occurs when the <see cref="ToolStripTrackBar.Value"/> property changes,
  196.        ''' either by movement of the scroll box or by manipulation in code.
  197.        ''' </summary>
  198.        <
  199.            Category("Action"), Description("Occurs when the Value property changes, either by movement of the scroll box or by manipulation in code.")
  200.        >
  201.        Public Event ValueChanged As EventHandler
  202.  
  203. #End Region
  204.  
  205. #Region " Constructors "
  206.  
  207.        ''' <summary>
  208.        ''' Initializes a new instance of the <see cref="ToolStripTrackBar"/> class.
  209.        ''' </summary>
  210.        Public Sub New()
  211.            MyBase.New(ToolStripTrackBar.CreateControlInstance())
  212.        End Sub
  213.  
  214. #End Region
  215.  
  216. #Region " Event Invocators "
  217.  
  218.        ''' <summary>
  219.        ''' Raises the <see cref="ToolStripTrackBar.Scroll"/> event.
  220.        ''' </summary>
  221.        '''
  222.        ''' <param name="sender">
  223.        ''' The source of the event.
  224.        ''' </param>
  225.        '''
  226.        ''' <param name="e">
  227.        ''' The <see cref="EventArgs"/> instance containing the event data.
  228.        ''' </param>
  229.        Private Sub OnScroll(sender As Object, e As EventArgs)
  230.            If Me.ScrollEvent IsNot Nothing Then
  231.                RaiseEvent Scroll(Me, e)
  232.            End If
  233.        End Sub
  234.  
  235.        ''' <summary>
  236.        ''' Raises the <see cref="ToolStripTrackBar.Scroll"/> event.
  237.        ''' </summary>
  238.        '''
  239.        ''' <param name="sender">
  240.        ''' The source of the event.
  241.        ''' </param>
  242.        '''
  243.        ''' <param name="e">
  244.        ''' The <see cref="EventArgs"/> instance containing the event data.
  245.        ''' </param>
  246.        Private Sub OnValueChanged(sender As Object, e As EventArgs)
  247.            If Me.ValueChangedEvent IsNot Nothing Then
  248.                RaiseEvent ValueChanged(Me, e)
  249.            End If
  250.        End Sub
  251.  
  252. #End Region
  253.  
  254. #Region " Event Invocators (Overriden) "
  255.  
  256.        ''' <summary>
  257.        ''' Subscribes events from the hosted control
  258.        ''' </summary>
  259.        '''
  260.        ''' <param name="control">
  261.        ''' The control from which to subscribe events.
  262.        ''' </param>
  263.        Protected Overrides Sub OnSubscribeControlEvents(control As Control)
  264.            MyBase.OnSubscribeControlEvents(control)
  265.  
  266.            AddHandler DirectCast(control, TrackBar).Scroll, AddressOf Me.OnScroll
  267.            AddHandler DirectCast(control, TrackBar).ValueChanged, AddressOf Me.OnValueChanged
  268.        End Sub
  269.  
  270.        ''' <summary>
  271.        ''' Unsubscribes events from the hosted control
  272.        ''' </summary>
  273.        '''
  274.        ''' <param name="control">
  275.        ''' The control from which to unsubscribe events.
  276.        ''' </param>
  277.        Protected Overrides Sub OnUnsubscribeControlEvents(control As Control)
  278.            MyBase.OnUnsubscribeControlEvents(control)
  279.  
  280.            RemoveHandler DirectCast(control, TrackBar).Scroll, AddressOf Me.OnScroll
  281.            RemoveHandler DirectCast(control, TrackBar).ValueChanged, AddressOf Me.Onvaluechanged
  282.        End Sub
  283.  
  284. #End Region
  285.  
  286. #Region " Private Methods "
  287.  
  288.        ''' <summary>
  289.        ''' Creates the control instance.
  290.        ''' </summary>
  291.        '''
  292.        ''' <returns>
  293.        ''' The control.
  294.        ''' </returns>
  295.        Private Shared Function CreateControlInstance() As Control
  296.            Using ts As New ToolStrip()
  297.                Return New TrackBar() With {
  298.                    .AutoSize = False,
  299.                    .Size = New Size(80, ts.Height)
  300.                }
  301.            End Using
  302.        End Function
  303.  
  304. #End Region
  305.  
  306.    End Class
  307.  
  308. End Namespace
  309.  
  310. #End Region
  311.  
  312.  
« Última modificación: 19 Abril 2024, 18:27 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

El siguiente código es un ejemplo oficial de Microsoft que sirve para modificar el fondo de pantalla (wallpaper) del escritorio.

El código está escrito originalmente en C#, lo he convertido a VB.NET, pero no lo he refactorizado, lo comparto tal cual.

Modo de empleo:
Código
  1. Dim supportJpgAsWallpaper As Boolean = Wallpaper.SupportJpgAsWallpaper
  2. Dim supportFitFillWallpaperStyles As Boolean = Wallpaper.SupportFitFillWallpaperStyles
  3.  
  4. Debug.WriteLine($"{NameOf(supportJpgAsWallpaper)}: {supportJpgAsWallpaper}")
  5. Debug.WriteLine($"{NameOf(supportFitFillWallpaperStyles)}: {supportFitFillWallpaperStyles}")
  6.  
  7. ' If supportJpgAsWallpaper AndAlso supportFitFillWallpaperStyles Then
  8.    Wallpaper.SetDesktopWallpaper("C:\wallpaper.jpg", WallpaperStyle.Fill)
  9. ' Else
  10. '   ...
  11. ' End If

Wallpaper.vb
Código
  1. Imports Microsoft.Win32
  2.  
  3. Imports System.ComponentModel
  4. Imports System.Drawing
  5. Imports System.Drawing.Imaging
  6. Imports System.IO
  7. Imports System.Runtime.InteropServices
  8.  
  9. '''********************************* Module Header ***********************************\
  10. '''Module Name:  Wallpaper.cs
  11. '''Project:      CSSetDesktopWallpaper
  12. '''Copyright (c) Microsoft Corporation.
  13. '''
  14. '''The file defines a wallpaper helper class.
  15. '''
  16. '''    Wallpaper.SetDesktopWallpaper(string fileName, WallpaperStyle style)
  17. '''
  18. '''This is the key method that sets the desktop wallpaper. The method body is composed of
  19. '''configuring the wallpaper style in the registry and setting the wallpaper with
  20. '''SystemParametersInfo.
  21. '''
  22. '''This source is subject to the Microsoft Public License.
  23. '''See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
  24. '''All other rights reserved.
  25. '''
  26. '''THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
  27. '''EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
  28. '''MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
  29. '''\************************************************************************************
  30. Public Module Wallpaper
  31. ''' <summary>
  32. ''' Determine if the fit and fill wallpaper styles are supported in
  33. ''' the current operating system. The styles are not supported before
  34. ''' Windows 7.
  35. ''' </summary>
  36. Public ReadOnly Property SupportFitFillWallpaperStyles As Boolean
  37. Get
  38. Return (Environment.OSVersion.Version >= New Version(6, 1))
  39. End Get
  40. End Property
  41.  
  42. ''' <summary>
  43. ''' Determine if .jpg files are supported as wallpaper in the current
  44. ''' operating system. The .jpg wallpapers are not supported before
  45. ''' Windows Vista.
  46. ''' </summary>
  47. Public ReadOnly Property SupportJpgAsWallpaper As Boolean
  48. Get
  49. Return (Environment.OSVersion.Version >= New Version(6, 0))
  50. End Get
  51. End Property
  52.  
  53. ''' <summary>
  54. ''' Set the desktop wallpaper.
  55. ''' </summary>
  56. ''' <param name="fileName">Path of the wallpaper</param>
  57. ''' <param name="style">Wallpaper style</param>
  58. Public Sub SetDesktopWallpaper(path As String, style As WallpaperStyle)
  59. ' Set the wallpaper style and tile.
  60. ' Two registry values are set in the Control Panel\Desktop key.
  61. ' TileWallpaper
  62. '  0: The wallpaper picture should not be tiled
  63. '  1: The wallpaper picture should be tiled
  64. ' WallpaperStyle
  65. '  0:  The image is centered if TileWallpaper=0 or tiled if TileWallpaper=1
  66. '  2:  The image is stretched to fill the screen
  67. '  6:  The image is resized to fit the screen while maintaining the aspect
  68. '      ratio. (Windows 7 and later)
  69. '  10: The image is resized and cropped to fill the screen while
  70. '      maintaining the aspect ratio. (Windows 7 and later)
  71. Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Control Panel\Desktop", True)
  72.  
  73. Select Case style
  74. Case WallpaperStyle.Tile
  75. key.SetValue("WallpaperStyle", "0")
  76. key.SetValue("TileWallpaper", "1")
  77. Case WallpaperStyle.Center
  78. key.SetValue("WallpaperStyle", "0")
  79. key.SetValue("TileWallpaper", "0")
  80. Case WallpaperStyle.Stretch
  81. key.SetValue("WallpaperStyle", "2")
  82. key.SetValue("TileWallpaper", "0")
  83. Case WallpaperStyle.Fit ' (Windows 7 and later)
  84. key.SetValue("WallpaperStyle", "6")
  85. key.SetValue("TileWallpaper", "0")
  86. Case WallpaperStyle.Fill ' (Windows 7 and later)
  87. key.SetValue("WallpaperStyle", "10")
  88. key.SetValue("TileWallpaper", "0")
  89. End Select
  90.  
  91. key.Close()
  92.  
  93. ' If the specified image file is neither .bmp nor .jpg, - or -
  94. ' if the image is a .jpg file but the operating system is Windows Server
  95. ' 2003 or Windows XP/2000 that does not support .jpg as the desktop
  96. ' wallpaper, convert the image file to .bmp and save it to the
  97. ' %appdata%\Microsoft\Windows\Themes folder.
  98. Dim ext As String = System.IO.Path.GetExtension(path)
  99. If (Not ext.Equals(".bmp", StringComparison.OrdinalIgnoreCase) AndAlso Not ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase)) OrElse (ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase) AndAlso Not SupportJpgAsWallpaper) Then
  100. Using image As Image = System.Drawing.Image.FromFile(path)
  101. path = String.Format("{0}\Microsoft\Windows\Themes\{1}.bmp", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.IO.Path.GetFileNameWithoutExtension(path))
  102. image.Save(path, ImageFormat.Bmp)
  103. End Using
  104. End If
  105.  
  106. ' Set the desktop wallpapaer by calling the NativeMethods API SystemParametersInfo
  107. ' with the SPI_SETDESKWALLPAPER desktop parameter. The changes should
  108. ' persist, and also be immediately visible.
  109. If Not SafeNativeMethods.SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE) Then
  110. Throw New Win32Exception()
  111. End If
  112. End Sub
  113.  
  114. Friend NotInheritable Class SafeNativeMethods
  115. <DllImport("user32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)>
  116. Public Shared Function SystemParametersInfo(uiAction As UInteger, uiParam As UInteger, pvParam As String, fWinIni As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean
  117. End Function
  118. End Class
  119.  
  120. Private Const SPI_SETDESKWALLPAPER As UInteger = 20
  121.  
  122. Private Const SPIF_UPDATEINIFILE As UInteger = &H1
  123.  
  124. Private Const SPIF_SENDWININICHANGE As UInteger = &H2
  125. End Module
  126.  
  127. Public Enum WallpaperStyle
  128. Tile
  129. Center
  130. Stretch
  131. Fit
  132. Fill
  133. End Enum
  134.  
« Última modificación: 19 Abril 2024, 18:59 pm por Eleкtro » En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.866



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

El siguiente código es un módulo por nombre 'Wildcard' que representa un algoritmo de coincidencia de cadenas con uso de comodines * (wildcards). Sirve como alternativa al operador Like de VB.NET.

Ejemplo de uso:

Código
  1. Dim input As String = "Hello World!"
  2. Dim pattern As String = "*e*l*o *!"
  3.  
  4. Console.WriteLine($"{NameOf(Wildcard.IsMatch)} {Wildcard.IsMatch(input, pattern)}")

El código lo he extraído del código fuente de la aplicación "RomyView" escrita en C#:


Lo he convertido a VB.NET de forma automática, y lo comparto tal cual, sin modificaciones ni adiciones. Lo he probado con varias cadenas y combinaciones de patrones de comodines, y parece funcionar a la perfección.

Wildcard.vb
Código
  1. ''' <summary>The IsMatch function below was downloaded from:
  2. ''' <a href="https://www.c-sharpcorner.com/uploadfile/b81385/efficient-string-matching-algorithm-with-use-of-wildcard-characters/">
  3. ''' Efficient String Matching Algorithm with Use of Wildcard Characters</a></summary>
  4. Public Module Wildcard
  5. ''' <summary>Tests whether specified string can be matched against provided pattern string, where
  6. ''' the pattern string may contain wildcards as follows: ? to replace any single character, and *
  7. ''' to replace any string.</summary>
  8. ''' <param name="input">String which is matched against the pattern.</param>
  9. ''' <param name="pattern">Pattern against which string is matched.</param>
  10. ''' <returns>true if <paramref name="pattern"/> matches the string <paramref name="input"/>; otherwise false.</returns>
  11. Public Function IsMatch(input As String, pattern As String) As Boolean
  12. Return IsMatch(input, pattern, "?"c, "*"c)
  13. End Function
  14.  
  15. ''' <summary>Tests whether specified string can be matched against provided pattern string.
  16. ''' Pattern may contain single- and multiple-replacing wildcard characters.</summary>
  17. ''' <param name="input">String which is matched against the pattern.</param>
  18. ''' <param name="pattern">Pattern against which string is matched.</param>
  19. ''' <param name="singleWildcard">Character which can be used to replace any single character in input string.</param>
  20. ''' <param name="multipleWildcard">Character which can be used to replace zero or more characters in input string.</param>
  21. ''' <returns>true if <paramref name="pattern"/> matches the string <paramref name="input"/>; otherwise false.</returns>
  22. Public Function IsMatch(input As String, pattern As String, singleWildcard As Char, multipleWildcard As Char) As Boolean
  23. Dim inputPosStack(((input.Length + 1) * (pattern.Length + 1)) - 1) As Integer ' Stack containing input positions that should be tested for further matching
  24. Dim patternPosStack(inputPosStack.Length - 1) As Integer ' Stack containing pattern positions that should be tested for further matching
  25. Dim stackPos As Integer = -1 ' Points to last occupied entry in stack; -1 indicates that stack is empty
  26. Dim pointTested()() As Boolean = {
  27. New Boolean(input.Length) {},
  28. New Boolean(pattern.Length) {}
  29. }
  30.  
  31. Dim inputPos As Integer = 0 ' Position in input matched up to the first multiple wildcard in pattern
  32. Dim patternPos As Integer = 0 ' Position in pattern matched up to the first multiple wildcard in pattern
  33.  
  34. ' Match beginning of the string until first multiple wildcard in pattern
  35. Do While inputPos < input.Length AndAlso patternPos < pattern.Length AndAlso pattern.Chars(patternPos) <> multipleWildcard AndAlso (input.Chars(inputPos) = pattern.Chars(patternPos) OrElse pattern.Chars(patternPos) = singleWildcard)
  36. inputPos += 1
  37. patternPos += 1
  38. Loop
  39.  
  40. ' Push this position to stack if it points to end of pattern or to a general wildcard
  41. If patternPos = pattern.Length OrElse pattern.Chars(patternPos) = multipleWildcard Then
  42. pointTested(0)(inputPos) = True
  43. pointTested(1)(patternPos) = True
  44.  
  45. stackPos += 1
  46. inputPosStack(stackPos) = inputPos
  47. patternPosStack(stackPos) = patternPos
  48. End If
  49. Dim matched As Boolean = False
  50.  
  51. ' Repeat matching until either string is matched against the pattern or no more parts remain on stack to test
  52. Do While stackPos >= 0 AndAlso Not matched
  53. inputPos = inputPosStack(stackPos) ' Pop input and pattern positions from stack
  54. patternPos = patternPosStack(stackPos) ' Matching will succeed if rest of the input string matches rest of the pattern
  55. stackPos -= 1
  56.  
  57. If inputPos = input.Length AndAlso patternPos = pattern.Length Then
  58. matched = True ' Reached end of both pattern and input string, hence matching is successful
  59. Else
  60. ' First character in next pattern block is guaranteed to be multiple wildcard
  61. ' So skip it and search for all matches in value string until next multiple wildcard character is reached in pattern
  62.  
  63. For curInputStart As Integer = inputPos To input.Length - 1
  64. Dim curInputPos As Integer = curInputStart
  65. Dim curPatternPos As Integer = patternPos + 1
  66.  
  67. If curPatternPos = pattern.Length Then ' Pattern ends with multiple wildcard, hence rest of the input string is matched with that character
  68. curInputPos = input.Length
  69. Else
  70. Do While curInputPos < input.Length AndAlso curPatternPos < pattern.Length AndAlso pattern.Chars(curPatternPos) <> multipleWildcard AndAlso (input.Chars(curInputPos) = pattern.Chars(curPatternPos) OrElse pattern.Chars(curPatternPos) = singleWildcard)
  71. curInputPos += 1
  72. curPatternPos += 1
  73. Loop
  74. End If
  75.  
  76. ' If we have reached next multiple wildcard character in pattern without breaking the matching sequence, then we have another candidate for full match
  77. ' This candidate should be pushed to stack for further processing
  78. ' At the same time, pair (input position, pattern position) will be marked as tested, so that it will not be pushed to stack later again
  79. If ((curPatternPos = pattern.Length AndAlso curInputPos = input.Length) OrElse (curPatternPos < pattern.Length AndAlso pattern.Chars(curPatternPos) = multipleWildcard)) AndAlso Not pointTested(0)(curInputPos) AndAlso Not pointTested(1)(curPatternPos) Then
  80. pointTested(0)(curInputPos) = True
  81. pointTested(1)(curPatternPos) = True
  82.  
  83. stackPos += 1
  84. inputPosStack(stackPos) = curInputPos
  85. patternPosStack(stackPos) = curPatternPos
  86. End If
  87. Next curInputStart
  88. End If
  89. Loop
  90.  
  91. Return matched
  92. End Function
  93. End Module
« Última modificación: 19 Abril 2024, 18:53 pm por Eleкtro » En línea



Páginas: 1 ... 44 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