Autor
|
Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) (Leído 529,352 veces)
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
Dos simples métodos para ocultar y restaurar las cabeceras de las pestañas de un TabControl: ''' <summary> ''' Provides extension methods for the <see cref="TabControl"/> class. ''' </summary> <HideModuleName> Public Module TabControlExtensions ''' --------------------------------------------------------------------------------------------------- ''' <summary> ''' Hides the tab headers of the source <see cref="TabControl"/>. ''' </summary> ''' --------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB"> ''' ' Create a TabControl instance ''' Dim myTabControl As New TabControl() ''' ''' ' Add some tabs to the TabControl ''' myTabControl.TabPages.Add("Tab 1") ''' myTabControl.TabPages.Add("Tab 2") ''' myTabControl.TabPages.Add("Tab 3") ''' ''' ' Display the TabControl in a Form ''' Me.Controls.Add(myTabControl) ''' myTabControl.BringToFront() ''' ''' ' Hide the tab headers ''' myTabControl.HideTabheaders() ''' </code> ''' </example> ''' --------------------------------------------------------------------------------------------------- ''' <param name="tabControl"> ''' The <see cref="TabControl"/> whose tab headers are to be hidden. ''' </param> ''' --------------------------------------------------------------------------------------------------- <Extension> <DebuggerStepThrough> Public Sub HideTabheaders(tabControl As TabControl) TabControlExtensions.ShowTabheaders(tabControl, TabSizeMode.Fixed, New Size(0, 1)) End Sub ''' --------------------------------------------------------------------------------------------------- ''' <summary> ''' Shows the tab headers of the source <see cref="TabControl"/>. ''' </summary> ''' --------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB"> ''' ' Create a TabControl instance ''' Dim myTabControl As New TabControl() ''' ''' ' Add some tabs to the TabControl ''' myTabControl.TabPages.Add("Tab 1") ''' myTabControl.TabPages.Add("Tab 2") ''' myTabControl.TabPages.Add("Tab 3") ''' ''' ' Display the TabControl in a Form ''' Me.Controls.Add(myTabControl) ''' myTabControl.BringToFront() ''' ''' ' Hide the tab headers ''' myTabControl.HideTabheaders() ''' ''' ' Show the tab headers with custom item size and filling to the right ''' myTabControl.ShowTabheaders(TabSizeMode.Normal, New Size(100, 50)) ''' </code> ''' </example> ''' --------------------------------------------------------------------------------------------------- ''' <param name="tabControl"> ''' The <see cref="TabControl"/> whose tab headers are to be shown. ''' </param> ''' ''' <param name="sizeMode"> ''' A value from <see cref="TabSizeMode"/> enumeration, that specifies the way that the control's tabs are sized. ''' </param> ''' ''' <param name="itemSize"> ''' Optional. The size of each tab header. ''' <para></para> ''' Default is <see cref="Size.Empty"/>, which is used to let the control automatically calculate the proper size ''' when <paramref name="sizeMode"/> is <see cref="TabSizeMode.Normal"/> or <see cref="TabSizeMode.FillToRight"/>. ''' </param> ''' --------------------------------------------------------------------------------------------------- <Extension> <DebuggerStepThrough> Public Sub ShowTabheaders(tabControl As TabControl, sizeMode As TabSizeMode, Optional itemSize As Size = Nothing) If itemSize = Nothing Then If sizeMode = TabSizeMode.Fixed Then Throw New ArgumentException("Value can't be null for fixed size mode.", paramName:=NameOf(itemSize)) End If itemSize = Size.Empty End If With tabControl .SuspendLayout() .ItemSize = itemSize .SizeMode = sizeMode .ResumeLayout(performLayout:=True) End With End Sub End Module
Modo de empleo utilizado en la imagen de demostración: Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Me.TabControl1.HideTabheaders() End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Me.TabControl1.ShowTabheaders(TabSizeMode.Normal) End Sub
|
|
« Última modificación: 11 Abril 2024, 02:30 am por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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: #Region " Imports " Imports System.ComponentModel Imports System.ComponentModel.Design Imports System.Runtime.InteropServices Imports System.Windows.Forms.Design #End Region #Region " ToolStripCheckBox " ''' <summary> ''' Represents a selectable <see cref="ToolStripItem"/> that when clicked, toggles a checkmark. ''' </summary> ''' <seealso cref="ToolStripControlHost"/> < ClassInterface(ClassInterfaceType.AutoDispatch), ComVisible(True), DebuggerStepThrough, DefaultEvent(NameOf(ToolStripCheckBox.CheckedChanged)), DefaultProperty(NameOf(ToolStripCheckBox.Text)), Description("Represents a selectable ToolStripItem that when clicked, toggles a checkmark."), Designer("System.Windows.Forms.Design.ToolStripItemDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), DesignerCategory(NameOf(DesignerCategoryAttribute.Generic)), DesignTimeVisible(False), DisplayName(NameOf(ToolStripCheckBox)), Localizable(True), ToolboxBitmap(GetType(CheckBox), "CheckBox.bmp"), ToolboxItem(False), ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Allow), ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip Or ToolStripItemDesignerAvailability.StatusStrip) > Public Class ToolStripCheckBox : Inherits ToolStripControlHost #Region " Properties " ''' <summary> ''' Gets the <see cref="CheckBox"/> control that is hosted by this <see cref="ToolStripCheckBox"/>. ''' </summary> < Browsable(True), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Category("Hosted"), Description("The CheckBox control that is hosted by this control.") > Public Shadows ReadOnly Property Control As CheckBox Get Return DirectCast(MyBase.Control, CheckBox) End Get End Property ''' <summary> ''' Gets or sets a value indicating whether this <see cref="ToolStripCheckBox"/> is in the checked state. ''' </summary> ''' ''' <returns> ''' <see langword="True"/> if checked; otherwise, <see langword="False"/>. ''' </returns> < Bindable(True), SettingsBindable(True), DefaultValue(False), RefreshProperties(RefreshProperties.All), Category("Appearance"), Description("Specifies whether this control is in the checked state.") > Public Property Checked As Boolean Get Return Me.Control.Checked End Get Set(value As Boolean) Me.Control.Checked = value End Set End Property ''' <summary> ''' Gets or sets the checked state of this <see cref="ToolStripCheckBox"/>. ''' </summary> ''' ''' <returns> ''' One of the <see cref="System.Windows.Forms.CheckState"/> enumeration values. ''' <para></para> ''' The default value is <see cref="System.Windows.Forms.CheckState.Unchecked"/>. ''' </returns> ''' ''' <exception cref="System.ComponentModel.InvalidEnumArgumentException"> ''' The value assigned is not one of the <see cref="System.Windows.Forms.CheckState"/> enumeration values. ''' </exception> < Bindable(True), DefaultValue(CheckState.Unchecked), RefreshProperties(RefreshProperties.All), Category("Appearance"), Description("Specifies the checked state of this control.") > Public Property CheckState As CheckState Get Return Me.Control.CheckState End Get Set(value As CheckState) Me.Control.CheckState = value End Set End Property ''' <summary> ''' Gets or sets a value indicating whether this <see cref="ToolStripCheckBox"/> ''' will allow three check states rather than two. ''' </summary> ''' ''' <remarks> ''' If the <see cref="ToolStripCheckBox.ThreeState"/> property is set to <see langword="False"/>, ''' the <see cref="ToolStripCheckBox.CheckState"/> property value can only be set to ''' the <see cref="System.Windows.Forms.CheckState.Indeterminate"/> value in code, ''' and not by user interaction doing click on the control. ''' </remarks> ''' ''' <returns> ''' <see langword="True"/> if this <see cref="ToolStripCheckBox"/> ''' is able to display three check states; otherwise, <see langword="False"/>. ''' <para></para> ''' The default value is <see langword="False"/>. ''' </returns> < DefaultValue(False), Category("Behavior"), Description("Specifies whether this control will allow three check states rather than two.") > Public Property ThreeState As Boolean Get Return Me.Control.ThreeState End Get Set(value As Boolean) Me.Control.ThreeState = value End Set End Property #End Region #Region " Events " ''' <summary> ''' Occurs whenever the <see cref="ToolStripCheckBox.Checked"/> property is changed. ''' </summary> Public Event CheckedChanged As EventHandler ''' <summary> ''' Occurs whenever the <see cref="ToolStripCheckBox.CheckState"/> property is changed. ''' </summary> Public Event CheckStateChanged As EventHandler #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="ToolStripCheckBox"/> class. ''' </summary> Public Sub New() MyBase.New(New CheckBox()) Me.Control.BackColor = Color.Transparent End Sub #End Region #Region " Event Invocators " ''' <summary> ''' Raises the <see cref="ToolStripCheckBox.CheckedChanged"/> event. ''' </summary> ''' ''' <param name="sender"> ''' The source of the event. ''' </param> ''' ''' <param name="e"> ''' The <see cref="EventArgs"/> instance containing the event data. ''' </param> Private Sub OnCheckedChanged(sender As Object, e As EventArgs) If Me.CheckedChangedEvent IsNot Nothing Then RaiseEvent CheckedChanged(Me, e) End If End Sub ''' <summary> ''' Raises the <see cref="ToolStripCheckBox.CheckStateChanged"/> event. ''' </summary> ''' ''' <param name="sender"> ''' The source of the event. ''' </param> ''' ''' <param name="e"> ''' The <see cref="EventArgs"/> instance containing the event data. ''' </param> Private Sub OnCheckStateChanged(sender As Object, e As EventArgs) If Me.CheckStateChangedEvent IsNot Nothing Then RaiseEvent CheckStateChanged(Me, e) End If End Sub #End Region #Region " Event Invocators (Overriden) " ''' <summary> ''' Subscribes events from the hosted control ''' </summary> ''' ''' <param name="control"> ''' The control from which to subscribe events. ''' </param> Protected Overrides Sub OnSubscribeControlEvents(control As Control) MyBase.OnSubscribeControlEvents(control) AddHandler DirectCast(control, CheckBox).CheckedChanged, AddressOf Me.OnCheckedChanged End Sub ''' <summary> ''' Unsubscribes events from the hosted control ''' </summary> ''' ''' <param name="control"> ''' The control from which to unsubscribe events. ''' </param> Protected Overrides Sub OnUnsubscribeControlEvents(control As Control) MyBase.OnUnsubscribeControlEvents(control) RemoveHandler DirectCast(control, CheckBox).CheckedChanged, AddressOf Me.OnCheckedChanged End Sub ''' <summary> ''' Raises the <see cref="Windows.Forms.Control.ParentChanged"/> event. ''' </summary> ''' ''' <param name="oldParent"> ''' The original parent of the item. ''' </param> ''' ''' <param name="newParent"> ''' The new parent of the item. ''' </param> Protected Overrides Sub OnParentChanged(oldParent As ToolStrip, newParent As ToolStrip) MyBase.OnParentChanged(oldParent, newParent) End Sub ''' <summary> ''' Raises the <see cref="ToolStripItem.OwnerChanged"/> event. ''' </summary> ''' ''' <param name="e"> ''' The <see cref="EventArgs"/> instance containing the event data. ''' </param> Protected Overrides Sub OnOwnerChanged(e As EventArgs) MyBase.OnOwnerChanged(e) End Sub #End Region End Class #End Region
|
|
« Última modificación: 11 Abril 2024, 12:25 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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. ''' <summary> ''' Specifies the type of paths that can be dragged in a drag&drop operation. ''' </summary> Public Enum PathDragType ''' <summary> ''' Only files can be dragged. ''' </summary> ''' <summary> ''' Only directories can be dragged. ''' </summary> Directories ''' <summary> ''' Both files and directories can be dragged. ''' </summary> Any End Enum ''' <summary> ''' Validates the <see cref="IDataObject"/> for a file or directory drag operation, ''' and returns the appropriate <see cref="DragDropEffects"/>. ''' <para></para> ''' This function should be called on the <see cref="Control.DragEnter"/> event handler of a control, ''' to assign its return value for the <see cref="DragEventArgs.Effect"/> property. ''' </summary> ''' ''' <example> This is a code example that shows how to validate a drag operation for a single file matching the specified file extensions. ''' <code language="VB"> ''' Private Sub TextBox1_DragEnter(sender As Object, e As DragEventArgs) Handles TextBox1.DragEnter ''' ''' Dim allowedFileExtensions As String() = {"avi", "mkv", "mp4"} ''' e.Effect = ValidatePathDrag(e.Data, PathDragType.Files, allowMultiplePaths:=False, allowedFileExtensions) ''' End Sub ''' ''' Private Sub TextBox1_DragDrop(sender As Object, e As DragEventArgs) Handles TextBox1.DragDrop ''' ''' If e.Data.GetDataPresent(DataFormats.FileDrop) AndAlso e.Effect = DragDropEffects.Copy Then ''' Dim singleFilePath As String = DirectCast(e.Data.GetData(DataFormats.FileDrop), String()).SingleOrDefault() ''' ''' Dim tb As TextBox = DirectCast(sender, TextBox) ''' tb.Text = singleFilePath ''' End If ''' End Sub ''' </code> ''' </example> ''' ''' <param name="data"> ''' The source <see cref="IDataObject"/> object to validate, ''' typically the object retrieved from <see cref="DragEventArgs.Data"/> property. ''' </param> ''' ''' <param name="allowedDragType"> ''' A <see cref="PathDragType"/> value that indicates the ''' type of paths allowed for the drag operation (files, directories, or any). ''' </param> ''' ''' <param name="allowMultiplePaths"> ''' A <see cref="Boolean"/> value indicating whether dragging multiple paths are allowed for the drag operation. ''' <para></para> ''' If this value is <see langword="False"/> and the <paramref name="data"/> object ''' contains multiple paths, <see cref="DragDropEffects.None"/> is returned. ''' </param> ''' ''' <param name="allowedFileExtensions"> ''' Optional. An array of file extensions to allow in a file drag operation. By default, all file extensions are allowed. ''' <para></para> ''' If any of the file paths contained in the <paramref name="data"/> object does not match ''' the specified allowed file extensions, <see cref="DragDropEffects.None"/> is returned. ''' <para></para> ''' This parameter has no effect for directories contained in the <paramref name="data"/> object. ''' </param> ''' ''' <returns> ''' Returns <see cref="DragDropEffects.Copy"/> If the drag validation was successful; ''' otherwise, returns <see cref="DragDropEffects.None"/>. ''' </returns> <DebuggerStepThrough> Public Shared Function ValidatePathDrag(data As IDataObject, allowedDragType As PathDragType, allowMultiplePaths As Boolean, ParamArray allowedFileExtensions As String()) As DragDropEffects Dim dataObject As DataObject = DirectCast(data, DataObject) If dataObject.ContainsFileDropList() Then Dim filePathList As New List(Of String) Dim pathList As StringCollection = dataObject.GetFileDropList() Dim pathListlength As Integer = pathList.Count ' Single/multiple path validation. If (Not allowMultiplePaths AndAlso pathListlength > 1) Then Return DragDropEffects.None End If Select Case allowedDragType ' Fails if path list contains any file. Case PathDragType.Directories For Each path As String In pathList If File. Exists(path ) Then Return DragDropEffects.None End If Next ' Fails if path list contains any directory. Case PathDragType. Files, PathDragType. Any For Each path As String In pathList If Directory.Exists(path) Then Return DragDropEffects.None End If ' Build the list of file paths, excluding any directory from the path list. filePathList.Add(path) Next End Select If allowedFileExtensions?.Any() AndAlso filePathList.Any() Then ' Trims the dot and white spaces to ensure that malformed file extension strings are corrected (eg. " .jpg" -> "jpg"). Dim allowedFileExtensionsLower As IEnumerable(Of String) = From ext As String In allowedFileExtensions Select ext.TrimStart({"."c, " "c}).ToLower() For Each filePath As String In filePathList ' Trims the dot from file extension strings (eg. ".jpg" -> "jpg"). Dim fileExtLower As String = IO.Path.GetExtension(filePath).TrimStart("."c).ToLower() If Not allowedFileExtensionsLower.Contains(fileExtLower) Then Return DragDropEffects.None End If Next End If Return DragDropEffects.Copy End If Return DragDropEffects.None End Function
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: Private Sub TextBox1_DragEnter(sender As Object, e As DragEventArgs) Handles TextBox1.DragEnter Dim allowedFileExtensions As String() = {"avi", "mkv", "mp4"} e. Effect = ValidatePathDrag (e. Data, PathDragType. Files, allowMultiplePaths: =False, allowedFileExtensions )End Sub Private Sub TextBox1_DragDrop(sender As Object, e As DragEventArgs) Handles TextBox1.DragDrop Dim singleFilePath As String = DirectCast(e.Data.GetData(DataFormats.FileDrop), String()).Single() Dim tb As TextBox = DirectCast(sender, TextBox) tb.Text = singleFilePath End Sub
|
|
« Última modificación: 11 Abril 2024, 18:36 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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: ' *********************************************************************** ' Author : ElektroStudios ' Modified : 12-April-2024 ' *********************************************************************** #Region " Public Members Summary " ' ToolStrip.ForEachItem(Boolean, Action(Of ToolStripItem)) ' ToolStrip.ForEachItem(Of T As ToolStripItem)(Boolean, Action(Of T)) #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Imports System.Windows.Forms #If Not NETCOREAPP Then Imports DevCase.ProjectMigration #Else Imports System.Runtime.Versioning #End If #End Region #Region " ToolStrip Extensions " ' ReSharper disable once CheckNamespace Namespace DevCase.Extensions.ToolStripExtensions ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Provides custom extension methods to use with <see cref="System.Windows.Forms.ToolStrip"/> class. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <HideModuleName> Public Module ToolStripExtensions #Region " Public Extension Methods " ''' --------------------------------------------------------------------------------------------------- ''' <summary> ''' Iterates through all the items of the specified type within the source <see cref="ToolStrip"/> control, ''' optionally recursively, and performs the specified action on each item. ''' </summary> ''' --------------------------------------------------------------------------------------------------- ''' <param name="toolStrip"> ''' The <see cref="ToolStrip"/> control whose items are to be iterated. ''' </param> ''' ''' <param name="recursive"> ''' <see langword="True"/> to iterate recursively through all items ''' (i.e., iterate the child items of child items); otherwise, <see langword="False"/>. ''' </param> ''' ''' <param name="action"> ''' The action to perform on each item. ''' </param> ''' --------------------------------------------------------------------------------------------------- <Extension> <DebuggerStepThrough> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ForEachItem(toolStrip As ToolStrip, recursive As Boolean, action As Action(Of ToolStripItem)) ToolStripExtensions.ForEachItem(Of ToolStripItem)(toolStrip, recursive, action) End Sub ''' --------------------------------------------------------------------------------------------------- ''' <summary> ''' Iterates through all the items of the specified type within the source <see cref="ToolStrip"/> control, ''' optionally recursively, and performs the specified action on each item. ''' </summary> ''' --------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' The type of items to iterate through. ''' </typeparam> ''' ''' <param name="toolStrip"> ''' The <see cref="ToolStrip"/> control whose items are to be iterated. ''' </param> ''' ''' <param name="recursive"> ''' <see langword="True"/> to iterate recursively through all items ''' (i.e., iterate the child items of child items); otherwise, <see langword="False"/>. ''' </param> ''' ''' <param name="action"> ''' The action to perform on each item. ''' </param> ''' --------------------------------------------------------------------------------------------------- <Extension> <DebuggerStepThrough> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ForEachItem(Of T As ToolStripItem)(toolStrip As ToolStrip, recursive As Boolean, action As Action(Of T)) If action Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(action), "Action cannot be null.") End If Dim queue As New Queue(Of ToolStripItem) ' First level items iteration. For Each item As ToolStripItem In toolStrip.Items If recursive Then queue.Enqueue(item) Else If TypeOf item Is T Then action.Invoke(DirectCast(item, T)) End If End If Next item ' Recursive items iteration. While queue.Any() Dim currentItem As ToolStripItem = queue.Dequeue() If TypeOf currentItem Is T Then action.Invoke(DirectCast(currentItem, T)) End If If TypeOf currentItem Is ToolStripDropDownItem Then Dim dropDownItem As ToolStripDropDownItem = DirectCast(currentItem, ToolStripDropDownItem) For Each subItem As ToolStripItem In dropDownItem.DropDownItems queue.Enqueue(subItem) Next subItem End If End While End Sub #End Region End Module End Namespace #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: <HideModuleName> public module ControlExtensions ''' --------------------------------------------------------------------------------------------------- ''' <summary> ''' Iterates through all controls within a parent <see cref="Control"/>, ''' optionally recursively, and performs the specified action on each control. ''' </summary> ''' --------------------------------------------------------------------------------------------------- ''' <param name="parentControl"> ''' The parent <see cref="Control"/> whose child controls are to be iterated. ''' </param> ''' ''' <param name="recursive"> ''' <see langword="True"/> to iterate recursively through all child controls ''' (i.e., iterate the child controls of child controls); otherwise, <see langword="False"/>. ''' </param> ''' ''' <param name="action"> ''' The action to perform on each control. ''' </param> ''' --------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ForEachControl(parentControl As Control, recursive As Boolean, action As Action(Of Control)) ControlExtensions.ForEachControl(Of Control)(parentControl, recursive, action) End Sub ''' --------------------------------------------------------------------------------------------------- ''' <summary> ''' Iterates through all controls of the specified type within a parent <see cref="Control"/>, ''' optionally recursively, and performs the specified action on each control. ''' </summary> ''' --------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' The type of child controls to iterate through. ''' </typeparam> ''' ''' <param name="parentControl"> ''' The parent <see cref="Control"/> whose child controls are to be iterated. ''' </param> ''' ''' <param name="recursive"> ''' <see langword="True"/> to iterate recursively through all child controls ''' (i.e., iterate the child controls of child controls); otherwise, <see langword="False"/>. ''' </param> ''' ''' <param name="action"> ''' The action to perform on each control. ''' </param> ''' --------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ForEachControl(Of T As Control)(parentControl As Control, recursive As Boolean, action As Action(Of T)) If TypeOf parentControl Is ToolStrip Then 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.") End If If action Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(action), "Action cannot be null.") End If Dim queue As New Queue(Of Control) ' First level items iteration. For Each control As Control In parentControl.Controls If recursive Then queue.Enqueue(control) Else If TypeOf control Is T Then action.Invoke(DirectCast(control, T)) End If End If Next control ' Recursive items iteration. While queue.Any() Dim currentControl As Control = queue.Dequeue() If TypeOf currentControl Is T Then action.Invoke(DirectCast(currentControl, T)) End If For Each childControl As Control In currentControl.Controls queue.Enqueue(childControl) Next childControl End While End Sub end module
|
|
« Última modificación: 12 Abril 2024, 05:09 am por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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:' Aplica recursos de localización a un form específico Dim form As Form = Me Dim cultureName As String = "es-ES" ApplyCultureResources(form, cultureName)
' Aplica recursos de localización a todos los forms de la aplicación Dim cultureName As String = "es-ES" ApplyCultureResources(cultureName)
Salida de depuración (ejemplo limitado):Cambio de idioma a Inglés: 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: 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: ''' <summary> ''' Provides extension methods for the <see cref="WinForms.IContainerControl"/> interface. ''' </summary> <HideModuleName> Public Module IContainerControlExtensions ''' <summary> ''' Gets the underlying <see cref="System.ComponentModel.ComponentCollection"/> collection ''' of the source <see cref="IContainerControl"/>. ''' </summary> ''' ''' <param name="container"> ''' The source <see cref="IContainerControl"/>. ''' </param> ''' ''' <returns> ''' The underlying <see cref="System.ComponentModel.ComponentCollection"/> collection ''' of the source <see cref="IContainerControl"/>. ''' </returns> <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Function GetComponentCollection(container As IContainerControl) As ComponentCollection Dim type As Type = container.GetType() Dim componentsField As FieldInfo = type.GetField("components", BindingFlags.NonPublic Or BindingFlags.Instance) If componentsField Is Nothing Then Throw New InvalidOperationException("""components"" field was not found through Reflection.") End If Dim containerComponents As IContainer = TryCast(componentsField.GetValue(container), IContainer) Return containerComponents?.Components End Function End Module
El código:''' <summary> ''' This method sets the current UI culture to the specified culture name, ''' then applies culture-specific resources to the specified <see cref="Form"/>, ''' to its controls and child controls, including menus and their items, and ''' the components in the form's <see cref="ComponentCollection"/>, recursively. ''' </summary> ''' ''' <example> This is a code example. ''' <code language="VB"> ''' Dim form As Form = Me ''' Dim cultureName As String = "es-ES" ''' ApplyCultureResources(form, cultureName) ''' </code> ''' </example> ''' ''' <param name="form"> ''' The form to apply resources to. ''' </param> ''' ''' <param name="cultureName"> ''' The culture name of the resources to apply. ''' </param> Public Shared Sub ApplyCultureResources(form As Form, cultureName As String) Dim culture As CultureInfo = CultureInfo.GetCultureInfo(cultureName) #If Not NETCOREAPP Then My.Application.ChangeUICulture(cultureName) #Else Thread.CurrentThread.CurrentUICulture = culture #End If Dim resources As New ComponentResourceManager(form.GetType()) ' Action delegate that applies resources to an IComponent. Dim applyResources As Action(Of IComponent, String) = Sub(component As IComponent, name As String) If String.IsNullOrEmpty(name) Then ' Not valid to apply localization resources. Exit Sub Else resources.ApplyResources(component, name, culture) End If ' Applies resources to the items and subitems of a ToolStrip component, recursively. If TypeOf component Is ToolStrip Then Dim ts As ToolStrip = DirectCast(component, ToolStrip) ToolStripExtensions.ForEachItem(ts, recursive:=True, Sub(item) applyResources(item, item.Name)) End If #If DEBUG Then ' Prints debug information. ' Flags to retrieve the "Text" property of a component. Const textPropBindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public Or BindingFlags.NonPublic Dim textProp As PropertyInfo = (From prop As PropertyInfo In component.GetType().GetProperties(textPropBindingFlags) Where prop.PropertyType Is GetType(String) AndAlso prop.Name.Equals("Text", StringComparison.OrdinalIgnoreCase) ).SingleOrDefault() Dim text As String = DirectCast(textProp?.GetValue(component), String) If String.IsNullOrEmpty(text) Then text = "(null)" End If Debug. WriteLine($ "Culture: {culture.EnglishName} ({culture.Name}), Component: {name,-40}, Text: {text}") #End If End Sub ' Apply resources to the form. applyResources(form, form.Name) ' Apply resources to the controls hosted in the form, recursively. FormExtensions.ForEachControl(form, recursive:=True, Sub(ctrl) applyResources(ctrl, ctrl.Name)) ' Apply resources to the components hosted in the ComponentCollection of the form. Dim components As ComponentCollection = IContainerControlExtensions.GetComponentCollection(form) If components IsNot Nothing Then ' Flags to retrieve the "Name" property of a component. Const namePropBindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public Or BindingFlags.NonPublic For Each component As IComponent In components Dim nameProp As PropertyInfo = (From prop As PropertyInfo In component.GetType().GetProperties(namePropBindingFlags) Where prop.PropertyType Is GetType(String) AndAlso prop.Name.Equals("Name", StringComparison.OrdinalIgnoreCase) ).SingleOrDefault() Dim name As String = DirectCast(nameProp?.GetValue(component), String) applyResources(component, name) Next component End If ' This code finds and applies resources to component fields declared at the form level ' (including those in the auto-generated code of the form designer) that doesn't have ' defined a "Name" property (such as NotifyIcon, ColorDialog, OpenFileDialog, etc). Const fieldsBindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.DeclaredOnly Or BindingFlags.Static Or BindingFlags.Public Or BindingFlags.NonPublic Dim fields As IEnumerable(Of FieldInfo) = From field As FieldInfo In form.GetType().GetFields(fieldsBindingFlags) Where GetType(IComponent).IsAssignableFrom(field.FieldType) AndAlso Not GetType(Control).IsAssignableFrom(field.FieldType) AndAlso Not GetType(ToolStripItem).IsAssignableFrom(field.FieldType) For Each field As FieldInfo In fields Dim component As IComponent = DirectCast(field.GetValue(form), IComponent) Dim name As String = field.Name.TrimStart("_"c) ' E.g.: "_NotifyIcon1" -> "NotifyIcon1" applyResources(component, name) Next field End Sub
''' <summary> ''' This method sets the current UI culture to the specified culture name, ''' then applies culture-specific resources to the open forms of the current application, ''' to its controls and child controls, including menus and their items, and ''' the components in the form's <see cref="ComponentCollection"/>, recursively. ''' </summary> ''' ''' <example> This is a code example. ''' <code language="VB"> ''' Dim cultureName As String = "es-ES" ''' ApplyCultureResources(cultureName) ''' </code> ''' </example> ''' ''' <param name="cultureName"> ''' The culture name of the resources to apply. ''' </param> Public Shared Sub ApplyCultureResources(cultureName As String) For Each form As Form In System.Windows.Forms.Application.OpenForms ApplyCultureResources(form, cultureName) Next form End Sub
|
|
« Última modificación: 15 Abril 2024, 14:42 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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: TabControl1.DisableTabs(TabPage1, TabPage2)
Para (re)activar una o varias pestañas: TabControl1.EnableTabs(TabPage1, TabPage2)
El Código:Imports System.Runtime.CompilerServices ''' <summary> ''' Provides extension methods for a <see cref="TabControl"/> control. ''' </summary> <HideModuleName> Public Module TabControlExtensions ''' <summary> ''' Collection used to store tab pages whose tab header need to remain disabled on a <see cref="TabControl"/>. ''' <para></para> ''' This collection depends on <see cref="TabControlExtensions.DisableOrEnableTabs_Internal"/> method. ''' </summary> Private disabledTabs As HashSet(Of TabPage) ''' <summary> ''' Collection used to store tab controls whose its <see cref="TabControl.Selecting"/> event ''' has been associated to <see cref="TabControlExtensions.disableTabPageHandler"/>. ''' <para></para> ''' This collection depends on <see cref="TabControlExtensions.DisableOrEnableTabs_Internal"/> method. ''' </summary> Private tabHandlerAddedControls As HashSet(Of TabControl) ''' <summary> ''' A <see cref="TabControlCancelEventHandler"/> delegate used for disabling tabs on a <see cref="TabControl"/>. ''' <para></para> ''' This handler depends on <see cref="TabControlExtensions.DisableOrEnableTabs_Internal"/> method. ''' </summary> Private tabDisablerHandler As TabControlCancelEventHandler ''' <summary> ''' Disables one or multiple <see cref="TabPage"/>, ''' making the tabs unselectable in the source <see cref="TabControl"/>. ''' </summary> ''' ''' <param name="tabControl"> ''' The source <see cref="TabControl"/>. ''' </param> ''' ''' <param name="tabPages"> ''' An Array of <see cref="TabPage"/> to disable. ''' </param> <Extension> <DebuggerStepThrough> Public Sub DisableTabs(tabControl As TabControl, ParamArray tabPages As TabPage()) TabControlExtensions.DisableOrEnableTabs_Internal(tabControl, enabled:=False, tabPages) End Sub ''' <summary> ''' Enables one or multiple <see cref="TabPage"/> that were previously ''' disabled by a call to <see cref="TabControlExtensions.DisableTabPages"/> method, ''' making the tabs selectable again in the source <see cref="TabControl"/>. ''' </summary> ''' ''' <param name="tabControl"> ''' The source <see cref="TabControl"/>. ''' </param> ''' ''' <param name="tabPages"> ''' An Array of <see cref="TabPage"/> to enable. ''' </param> <Extension> <DebuggerStepThrough> Public Sub EnableTabs(tabControl As TabControl, ParamArray tabPages As TabPage()) TabControlExtensions.DisableOrEnableTabs_Internal(tabControl, enabled:=True, tabPages) End Sub ''' <summary> ''' *** FOR INTERNAL USE ONLY *** ''' <para></para> ''' Disables or enables one or multiple <see cref="TabPage"/>, ''' denying or allowing their tab selection in the source <see cref="TabControl"/>. ''' </summary> ''' ''' <param name="tabControl"> ''' The source <see cref="TabControl"/>. ''' </param> ''' ''' <param name="enabled"> ''' If <see langword="False"/>, disables the tab pages and make them unselectable in the source <see cref="TabControl"/>; ''' otherwise, enable the tab pages and allows to be selected in the source <see cref="TabControl"/>. ''' </param> ''' ''' <param name="tabPages"> ''' An Array of the tab pages to disable or enable. ''' </param> <DebuggerStepThrough> Private Sub DisableOrEnableTabs_Internal(tabControl As TabControl, enabled As Boolean, ParamArray tabPages As TabPage()) If tabControl Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(tabControl)) End If If tabPages Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(tabPages)) End If ' Initialize collections. If TabControlExtensions.disabledTabs Is Nothing Then TabControlExtensions.disabledTabs = New HashSet(Of TabPage) End If If TabControlExtensions.tabHandlerAddedControls Is Nothing Then TabControlExtensions.tabHandlerAddedControls = New HashSet(Of TabControl) End If ' Initialize handler. If TabControlExtensions.tabDisablerHandler Is Nothing Then TabControlExtensions.tabDisablerHandler = Sub(sender As Object, e As TabControlCancelEventArgs) If e.TabPageIndex < 0 Then Exit Sub End If Select Case e.Action Case TabControlAction.Selecting, TabControlAction.Selected e.Cancel = TabControlExtensions.disabledTabs.Contains(e.TabPage) Case Else Exit Sub End Select End Sub End If For Each tabPage As TabPage In tabPages If tabPage Is Nothing Then Throw New NullReferenceException($"{NameOf(tabPage)} object is null.") End If ' Disable or enable the tab page. tabPage.Enabled = enabled If Not enabled Then ' Disable the tab header. Dim success As Boolean = disabledTabs.Add(tabPage) If success AndAlso Not TabControlExtensions.tabHandlerAddedControls.Contains(tabControl) Then AddHandler tabControl.Selecting, TabControlExtensions.tabDisablerHandler TabControlExtensions.tabHandlerAddedControls.Add(tabControl) End If Else ' Enable the tab header. Dim success As Boolean = disabledTabs.Remove(tabPage) If success AndAlso TabControlExtensions.tabHandlerAddedControls.Contains(tabControl) AndAlso Not TabControlExtensions.disabledTabs.Any() Then RemoveHandler tabControl.Selecting, TabControlExtensions.tabDisablerHandler TabControlExtensions.tabHandlerAddedControls.Remove(tabControl) End If End If Next tabPage End Sub End Module
|
|
« Última modificación: 16 Abril 2024, 12:26 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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:Dim menuItem As ToolStripMenuItem = Me.ToolStripMenuItem1 Dim preventClosure As Boolean = True Dim recursive As Boolean = False menuItem.SetClosureBehaviorOnClick(preventClosure, recursive)
El código:' *********************************************************************** ' Author : ElektroStudios ' Modified : 12-April-2024 ' *********************************************************************** #Region " Public Members Summary " ' ToolStripMenuItem.SetClosureBehaviorOnClick(Boolean, Boolean) #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.ComponentModel Imports System.Linq Imports System.Runtime.CompilerServices Imports System.Windows.Forms #End Region #Region " ToolStripMenuItem Extensions " Namespace DevCase.Core.Extensions ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Provides extension methods to use with the <see cref="ToolStripMenuItem"/> class. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <HideModuleName> Public Module ToolStripMenuItemExtensions #Region " Public Extension Methods " ''' <summary> ''' A <see cref="ToolStripDropDownClosingEventHandler"/> delegate used to control ''' the <see cref="ToolStripDropDown.Closing"/> event of a <see cref="ToolStripDropDown"/>. ''' <para></para> ''' This handler depends on <see cref="ToolStripMenuItemExtensions.SetClosureBehaviorOnClick"/> method. ''' </summary> Private closingHandler As ToolStripDropDownClosingEventHandler ''' <summary> ''' A collection of <see cref="ToolStripDropDown"/> items ''' whose <see cref="ToolStripDropDown.Closing"/> event ''' has been associated to <see cref="ToolStripMenuItemExtensions.closingHandler"/>. ''' <para></para> ''' This collection depends on <see cref="ToolStripMenuItemExtensions.SetClosureBehaviorOnClick"/> method. ''' </summary> Private closingHandlerAssociatedItems As HashSet(Of ToolStripDropDown) ''' <summary> ''' Sets the closure behavior for the source <see cref="ToolStripMenuItem"/> when its drop-down items are clicked. ''' </summary> ''' ''' <remarks> ''' This method associates the underlying ''' <see cref="ToolStripMenuItem.DropDown"/>'s <see cref="ToolStripDropDown.Closing"/> event ''' with a handler to control the closure behavior. ''' </remarks> ''' ''' <example> This is a code example. ''' <code language="VB"> ''' Dim menuItem As ToolStripMenuItem = Me.ToolStripMenuItem1 ''' Dim preventClosure As Boolean = True ''' Dim recursive As Boolean = True ''' ''' menuItem.SetClosureBehaviorOnClick(preventClosure, recursive) ''' </code> ''' </example> ''' ''' <param name="menuItem"> ''' The <see cref="ToolStripMenuItem"/> to set the closure behavior for. ''' </param> ''' ''' <param name="preventClosure"> ''' <see langword="True"/> to prevent closure of the source <see cref="ToolStripMenuItem"/> ''' when its drop-down items are clicked; otherwise, <see langword="False"/>. ''' </param> <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub SetClosureBehaviorOnClick(menuItem As ToolStripMenuItem, preventClosure As Boolean, recursive As Boolean) If menuItem Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(menuItem)) End If If Not menuItem.HasDropDown Then Throw New InvalidOperationException( "The ToolStripDropDownItem.DropDown for the ToolStripDropDownItem has not been created.") End If If ToolStripMenuItemExtensions.closingHandler Is Nothing Then ToolStripMenuItemExtensions.closingHandler = Sub(sender As Object, e As ToolStripDropDownClosingEventArgs) e.Cancel = (e.CloseReason = ToolStripDropDownCloseReason.ItemClicked) End Sub End If If ToolStripMenuItemExtensions.closingHandlerAssociatedItems Is Nothing Then ToolStripMenuItemExtensions.closingHandlerAssociatedItems = New HashSet(Of ToolStripDropDown) End If Dim dropdownAction As Action(Of ToolStripDropDown) = Sub(dropdown As ToolStripDropDown) If preventClosure Then If Not ToolStripMenuItemExtensions.closingHandlerAssociatedItems.Contains(dropdown) Then AddHandler dropdown.Closing, ToolStripMenuItemExtensions.closingHandler ToolStripMenuItemExtensions.closingHandlerAssociatedItems.Add(dropdown) End If Else If ToolStripMenuItemExtensions.closingHandlerAssociatedItems.Contains(dropdown) Then RemoveHandler dropdown.Closing, ToolStripMenuItemExtensions.closingHandler ToolStripMenuItemExtensions.closingHandlerAssociatedItems.Remove(dropdown) End If End If End Sub Dim queue As New Queue(Of ToolStripDropDown) ' Root level items iteration. If recursive Then queue.Enqueue(menuItem.DropDown) Else If TypeOf menuItem Is ToolStripMenuItem Then dropdownAction(menuItem.DropDown) End If End If ' Recursive items iteration. While queue.Any() Dim currentItem As ToolStripDropDown = queue.Dequeue() dropdownAction(currentItem) If currentItem.HasChildren Then For Each subMenuItem As ToolStripMenuItem In currentItem.Items.OfType(Of ToolStripMenuItem) If subMenuItem.HasDropDown Then queue.Enqueue(subMenuItem.DropDown) End If Next End If End While End Sub #End Region End Module End Namespace #End Region
|
|
« Última modificación: 16 Abril 2024, 13:43 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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' *********************************************************************** ' Author : ElektroStudios ' Modified : 19-April-2024 ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.ComponentModel Imports System.Drawing Imports System.Runtime.InteropServices Imports System.Windows.Forms Imports System.Windows.Forms.Design #End Region #Region " ToolStripNumericUpDown " ' ReSharper disable once CheckNamespace Namespace DevCase.UI.Components ''' <summary> ''' Represents a selectable Windows spin box <see cref="ToolStripItem"/> that displays numeric values. ''' </summary> ''' <seealso cref="ToolStripControlHost"/> < ComVisible(True), DebuggerStepThrough, DefaultEvent(NameOf(ToolStripNumericUpDown.ValueChanged)), DefaultProperty(NameOf(ToolStripNumericUpDown.Value)), DefaultBindingProperty(NameOf(ToolStripNumericUpDown.Value)), Description("Represents a selectable Windows spin box ToolStripItem that displays numeric values."), Designer("System.Windows.Forms.Design.ToolStripItemDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), DesignerCategory(NameOf(DesignerCategoryAttribute.Generic)), DesignTimeVisible(False), DisplayName(NameOf(ToolStripNumericUpDown)), Localizable(True), ToolboxBitmap(GetType(NumericUpDown), "NumericUpDown.bmp"), ToolboxItem(False), ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Allow), ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip Or ToolStripItemDesignerAvailability.StatusStrip) > Public Class ToolStripNumericUpDown : Inherits ToolStripControlHost #Region " Properties " ''' <summary> ''' Gets the <see cref="NumericUpDown"/> control that is hosted by this <see cref="ToolStripNumericUpDown"/>. ''' </summary> < Browsable(True), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Category("Components"), Description("The NumericUpDown control that is hosted by this control.") > Public Shadows ReadOnly Property Control As NumericUpDown Get Return DirectCast(MyBase.Control, NumericUpDown) End Get End Property ''' <summary> ''' Gets or sets the numeric value assigned to this <see cref="ToolStripNumericUpDown"/>. ''' </summary> ''' ''' <value> ''' The numeric value assigned to this <see cref="ToolStripNumericUpDown"/>. ''' </value> < Bindable(True), DefaultValue(0D), Category("Appearance"), Description("The numeric value assigned to this control.") > Public Property Value As Decimal Get Return Me.Control.Value End Get Set(value As Decimal) Me.Control.Value = value End Set End Property ''' <summary> ''' Gets or sets the text to be displayed in this <see cref="ToolStripNumericUpDown"/>. ''' </summary> ''' ''' <value> ''' The text to be displayed in this <see cref="ToolStripNumericUpDown"/>. ''' </value> < Browsable(False), EditorBrowsable(EditorBrowsableState.Never), Bindable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Category("Behavior"), Description("The text to be displayed in this control.") > Public Overrides Property Text As String Get Return Me.Control.Text End Get Set(value As String) Me.Control.Text = value End Set End Property ''' <summary> ''' This property is not applicable for this control. ''' </summary> < Browsable(False), EditorBrowsable(EditorBrowsableState.Never), Category("Not Applicable"), Description("This property is not applicable for this control.") > Public Overrides Property BackgroundImage As Image Get Return Nothing End Get Set(value As Image) MyBase.BackgroundImage = Nothing End Set End Property ''' <summary> ''' This property is not applicable for this control. ''' </summary> < Browsable(False), EditorBrowsable(EditorBrowsableState.Never), Category("Not Applicable"), Description("This property is not applicable for this control.") > Public Overrides Property BackgroundImageLayout As ImageLayout Get Return MyBase.BackgroundImageLayout End Get Set(value As ImageLayout) MyBase.BackgroundImageLayout = value End Set End Property ''' <summary> ''' This property is not applicable for this control. ''' </summary> < Browsable(False), EditorBrowsable(EditorBrowsableState.Never), Category("Not Applicable"), Description("This property is not applicable for this control.") > Public Overrides Property Image As Image Get Return Nothing End Get Set(value As Image) MyBase.Image = Nothing End Set End Property #End Region #Region " Events " ''' <summary> ''' Occurs whenever the <see cref="ToolStripNumericUpDown.Value"/> property is changed. ''' </summary> < Category("Action"), Description("Occurs whenever the Value property is changed.") > Public Event ValueChanged As EventHandler #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="ToolStripNumericUpDown"/> class. ''' </summary> Public Sub New() MyBase.New(ToolStripNumericUpDown.CreateControlInstance()) End Sub #End Region #Region " Event Invocators " ''' <summary> ''' Raises the <see cref="ToolStripNumericUpDown.ValueChanged"/> event. ''' </summary> ''' ''' <param name="sender"> ''' The source of the event. ''' </param> ''' ''' <param name="e"> ''' The <see cref="EventArgs"/> instance containing the event data. ''' </param> Private Sub OnValueChanged(sender As Object, e As EventArgs) If Me.ValueChangedEvent IsNot Nothing Then RaiseEvent ValueChanged(Me, e) End If End Sub #End Region #Region " Event Invocators (Overriden) " ''' <summary> ''' Subscribes events from the hosted control ''' </summary> ''' ''' <param name="control"> ''' The control from which to subscribe events. ''' </param> Protected Overrides Sub OnSubscribeControlEvents(control As Control) MyBase.OnSubscribeControlEvents(control) AddHandler DirectCast(control, NumericUpDown).ValueChanged, AddressOf Me.OnValueChanged End Sub ''' <summary> ''' Unsubscribes events from the hosted control ''' </summary> ''' ''' <param name="control"> ''' The control from which to unsubscribe events. ''' </param> Protected Overrides Sub OnUnsubscribeControlEvents(control As Control) MyBase.OnUnsubscribeControlEvents(control) RemoveHandler DirectCast(control, NumericUpDown).ValueChanged, AddressOf Me.OnValueChanged End Sub #End Region #Region " Private Methods " ''' <summary> ''' Creates the control instance. ''' </summary> ''' ''' <returns> ''' The control. ''' </returns> Private Shared Function CreateControlInstance() As Control Return New NumericUpDown() With {.AutoSize = True} End Function #End Region End Class End Namespace #End Region
ToolStripTrackBar.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 19-April-2024 ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.ComponentModel Imports System.Drawing Imports System.Runtime.InteropServices Imports System.Windows.Forms Imports System.Windows.Forms.Design #End Region #Region " ToolStripTrackBar " ' ReSharper disable once CheckNamespace Namespace DevCase.UI.Components ''' <summary> ''' Represents a selectable track bar <see cref="ToolStripItem"/>. ''' </summary> ''' <seealso cref="ToolStripControlHost"/> < ComVisible(True), DebuggerStepThrough, DefaultEvent(NameOf(ToolStripTrackBar.Scroll)), DefaultProperty(NameOf(ToolStripTrackBar.Value)), DefaultBindingProperty(NameOf(ToolStripTrackBar.Value)), Description("Represents a selectable track bar ToolStripItem."), Designer("System.Windows.Forms.Design.ToolStripItemDesigner, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), DesignerCategory(NameOf(DesignerCategoryAttribute.Generic)), DesignTimeVisible(False), DisplayName(NameOf(ToolStripTrackBar)), Localizable(True), ToolboxBitmap(GetType(TrackBar), "TrackBar.bmp"), ToolboxItem(False), ToolboxItemFilter("System.Windows.Forms", ToolboxItemFilterType.Allow), ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip Or ToolStripItemDesignerAvailability.StatusStrip) > Public Class ToolStripTrackBar : Inherits ToolStripControlHost #Region " Properties " ''' <summary> ''' Gets the <see cref="TrackBar"/> control that is hosted by this <see cref="ToolStripTrackBar"/>. ''' </summary> < Browsable(True), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Category("Components"), Description("The TrackBar control that is hosted by this control.") > Public Shadows ReadOnly Property Control As TrackBar Get Return DirectCast(MyBase.Control, TrackBar) End Get End Property ''' <summary> ''' Gets or sets a numeric value that represents the current position of the scroll box on this <see cref="ToolStripTrackBar"/>. ''' </summary> ''' ''' <value> ''' The numeric value that represents the current position of the scroll box on this <see cref="ToolStripTrackBar"/>. ''' </value> < Bindable(True), DefaultValue(0I), Category("Behavior"), Description("The numeric value that represents the current position of the scroll box on this control.") > Public Property Value As Integer Get Return Me.Control.Value End Get Set(value As Integer) Me.Control.Value = value End Set End Property ''' <summary> ''' Gets or sets the lower limit of the range this <see cref="ToolStripTrackBar"/> is working with. ''' </summary> ''' ''' <value> ''' The minimum value for this <see cref="ToolStripTrackBar"/>. The default is 0. ''' </value> < Bindable(True), DefaultValue(0I), RefreshProperties(RefreshProperties.All), Category("Behavior"), Description("The minimum value for this control.") > Public Property Minimum As Integer Get Return Me.Control.Minimum End Get Set(value As Integer) Me.Control.Minimum = value End Set End Property ''' <summary> ''' Gets or sets the upper limit of the range this <see cref="ToolStripTrackBar"/> is working with. ''' </summary> ''' ''' <value> ''' The maximum value for this <see cref="ToolStripTrackBar"/>. The default is 10. ''' </value> < Bindable(True), DefaultValue(10I), RefreshProperties(RefreshProperties.All), Category("Behavior"), Description("The maximum value for this control.") > Public Property Maximum As Integer Get Return Me.Control.Maximum End Get Set(value As Integer) Me.Control.Maximum = value End Set End Property ''' <summary> ''' This property is not applicable for this control. ''' </summary> < Browsable(False), EditorBrowsable(EditorBrowsableState.Never), Category("Not Applicable"), Description("This property is not applicable for this control.") > Public Overrides Property BackgroundImage As Image Get Return Nothing End Get Set(value As Image) MyBase.BackgroundImage = Nothing End Set End Property ''' <summary> ''' This property is not applicable for this control. ''' </summary> < Browsable(False), EditorBrowsable(EditorBrowsableState.Never), Category("Not Applicable"), Description("This property is not applicable for this control.") > Public Overrides Property BackgroundImageLayout As ImageLayout Get Return MyBase.BackgroundImageLayout End Get Set(value As ImageLayout) MyBase.BackgroundImageLayout = value End Set End Property ''' <summary> ''' This property is not applicable for this control. ''' </summary> < Browsable(False), EditorBrowsable(EditorBrowsableState.Never), Category("Not Applicable"), Description("This property is not applicable for this control.") > Public Overrides Property Image As Image Get Return Nothing End Get Set(value As Image) MyBase.Image = Nothing End Set End Property #End Region #Region " Events " ''' <summary> ''' Occurs when either a mouse or keyboard action moves the scroll box. ''' </summary> < Category("Behavior"), Description("Occurs when either a mouse or keyboard action moves the scroll box.") > Public Event Scroll As EventHandler ''' <summary> ''' Occurs when the <see cref="ToolStripTrackBar.Value"/> property changes, ''' either by movement of the scroll box or by manipulation in code. ''' </summary> < Category("Action"), Description("Occurs when the Value property changes, either by movement of the scroll box or by manipulation in code.") > Public Event ValueChanged As EventHandler #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="ToolStripTrackBar"/> class. ''' </summary> Public Sub New() MyBase.New(ToolStripTrackBar.CreateControlInstance()) End Sub #End Region #Region " Event Invocators " ''' <summary> ''' Raises the <see cref="ToolStripTrackBar.Scroll"/> event. ''' </summary> ''' ''' <param name="sender"> ''' The source of the event. ''' </param> ''' ''' <param name="e"> ''' The <see cref="EventArgs"/> instance containing the event data. ''' </param> Private Sub OnScroll(sender As Object, e As EventArgs) If Me.ScrollEvent IsNot Nothing Then RaiseEvent Scroll(Me, e) End If End Sub ''' <summary> ''' Raises the <see cref="ToolStripTrackBar.Scroll"/> event. ''' </summary> ''' ''' <param name="sender"> ''' The source of the event. ''' </param> ''' ''' <param name="e"> ''' The <see cref="EventArgs"/> instance containing the event data. ''' </param> Private Sub OnValueChanged(sender As Object, e As EventArgs) If Me.ValueChangedEvent IsNot Nothing Then RaiseEvent ValueChanged(Me, e) End If End Sub #End Region #Region " Event Invocators (Overriden) " ''' <summary> ''' Subscribes events from the hosted control ''' </summary> ''' ''' <param name="control"> ''' The control from which to subscribe events. ''' </param> Protected Overrides Sub OnSubscribeControlEvents(control As Control) MyBase.OnSubscribeControlEvents(control) AddHandler DirectCast(control, TrackBar).Scroll, AddressOf Me.OnScroll AddHandler DirectCast(control, TrackBar).ValueChanged, AddressOf Me.OnValueChanged End Sub ''' <summary> ''' Unsubscribes events from the hosted control ''' </summary> ''' ''' <param name="control"> ''' The control from which to unsubscribe events. ''' </param> Protected Overrides Sub OnUnsubscribeControlEvents(control As Control) MyBase.OnUnsubscribeControlEvents(control) RemoveHandler DirectCast(control, TrackBar).Scroll, AddressOf Me.OnScroll RemoveHandler DirectCast(control, TrackBar).ValueChanged, AddressOf Me.Onvaluechanged End Sub #End Region #Region " Private Methods " ''' <summary> ''' Creates the control instance. ''' </summary> ''' ''' <returns> ''' The control. ''' </returns> Private Shared Function CreateControlInstance() As Control Using ts As New ToolStrip() Return New TrackBar() With { .AutoSize = False, .Size = New Size(80, ts.Height) } End Using End Function #End Region End Class End Namespace #End Region
|
|
« Última modificación: 19 Abril 2024, 18:27 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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: Dim supportJpgAsWallpaper As Boolean = Wallpaper.SupportJpgAsWallpaper Dim supportFitFillWallpaperStyles As Boolean = Wallpaper.SupportFitFillWallpaperStyles Debug. WriteLine($ "{NameOf(supportJpgAsWallpaper)}: {supportJpgAsWallpaper}") Debug. WriteLine($ "{NameOf(supportFitFillWallpaperStyles)}: {supportFitFillWallpaperStyles}") ' If supportJpgAsWallpaper AndAlso supportFitFillWallpaperStyles Then Wallpaper.SetDesktopWallpaper("C:\wallpaper.jpg", WallpaperStyle.Fill) ' Else ' ... ' End If
Wallpaper.vbImports Microsoft.Win32 Imports System.ComponentModel Imports System.Drawing Imports System.Drawing.Imaging Imports System.IO Imports System.Runtime.InteropServices '''********************************* Module Header ***********************************\ '''Module Name: Wallpaper.cs '''Project: CSSetDesktopWallpaper '''Copyright (c) Microsoft Corporation. ''' '''The file defines a wallpaper helper class. ''' ''' Wallpaper.SetDesktopWallpaper(string fileName, WallpaperStyle style) ''' '''This is the key method that sets the desktop wallpaper. The method body is composed of '''configuring the wallpaper style in the registry and setting the wallpaper with '''SystemParametersInfo. ''' '''This source is subject to the Microsoft Public License. '''See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. '''All other rights reserved. ''' '''THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER '''EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF '''MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. '''\************************************************************************************ Public Module Wallpaper ''' <summary> ''' Determine if the fit and fill wallpaper styles are supported in ''' the current operating system. The styles are not supported before ''' Windows 7. ''' </summary> Public ReadOnly Property SupportFitFillWallpaperStyles As Boolean Get Return (Environment.OSVersion.Version >= New Version(6, 1)) End Get End Property ''' <summary> ''' Determine if .jpg files are supported as wallpaper in the current ''' operating system. The .jpg wallpapers are not supported before ''' Windows Vista. ''' </summary> Public ReadOnly Property SupportJpgAsWallpaper As Boolean Get Return (Environment.OSVersion.Version >= New Version(6, 0)) End Get End Property ''' <summary> ''' Set the desktop wallpaper. ''' </summary> ''' <param name="fileName">Path of the wallpaper</param> ''' <param name="style">Wallpaper style</param> Public Sub SetDesktopWallpaper(path As String, style As WallpaperStyle) ' Set the wallpaper style and tile. ' Two registry values are set in the Control Panel\Desktop key. ' TileWallpaper ' 0: The wallpaper picture should not be tiled ' 1: The wallpaper picture should be tiled ' WallpaperStyle ' 0: The image is centered if TileWallpaper=0 or tiled if TileWallpaper=1 ' 2: The image is stretched to fill the screen ' 6: The image is resized to fit the screen while maintaining the aspect ' ratio. (Windows 7 and later) ' 10: The image is resized and cropped to fill the screen while ' maintaining the aspect ratio. (Windows 7 and later) Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey("Control Panel\Desktop", True) Select Case style Case WallpaperStyle.Tile key.SetValue("WallpaperStyle", "0") key.SetValue("TileWallpaper", "1") Case WallpaperStyle.Center key.SetValue("WallpaperStyle", "0") key.SetValue("TileWallpaper", "0") Case WallpaperStyle.Stretch key.SetValue("WallpaperStyle", "2") key.SetValue("TileWallpaper", "0") Case WallpaperStyle.Fit ' (Windows 7 and later) key.SetValue("WallpaperStyle", "6") key.SetValue("TileWallpaper", "0") Case WallpaperStyle.Fill ' (Windows 7 and later) key.SetValue("WallpaperStyle", "10") key.SetValue("TileWallpaper", "0") End Select key.Close() ' If the specified image file is neither .bmp nor .jpg, - or - ' if the image is a .jpg file but the operating system is Windows Server ' 2003 or Windows XP/2000 that does not support .jpg as the desktop ' wallpaper, convert the image file to .bmp and save it to the ' %appdata%\Microsoft\Windows\Themes folder. Dim ext As String = System.IO.Path.GetExtension(path) If (Not ext.Equals(".bmp", StringComparison.OrdinalIgnoreCase) AndAlso Not ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase)) OrElse (ext.Equals(".jpg", StringComparison.OrdinalIgnoreCase) AndAlso Not SupportJpgAsWallpaper) Then Using image As Image = System.Drawing.Image.FromFile(path) path = String.Format("{0}\Microsoft\Windows\Themes\{1}.bmp", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.IO.Path.GetFileNameWithoutExtension(path)) image.Save(path, ImageFormat.Bmp) End Using End If ' Set the desktop wallpapaer by calling the NativeMethods API SystemParametersInfo ' with the SPI_SETDESKWALLPAPER desktop parameter. The changes should ' persist, and also be immediately visible. If Not SafeNativeMethods.SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE) Then Throw New Win32Exception() End If End Sub Friend NotInheritable Class SafeNativeMethods <DllImport("user32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function SystemParametersInfo(uiAction As UInteger, uiParam As UInteger, pvParam As String, fWinIni As UInteger) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function End Class Private Const SPI_SETDESKWALLPAPER As UInteger = 20 Private Const SPIF_UPDATEINIFILE As UInteger = &H1 Private Const SPIF_SENDWININICHANGE As UInteger = &H2 End Module Public Enum WallpaperStyle Tile Center Stretch Fit Fill End Enum
|
|
« Última modificación: 19 Abril 2024, 18:59 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.878
|
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: Dim input As String = "Hello World!" Dim pattern As String = "*e*l*o *!" 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''' <summary>The IsMatch function below was downloaded from: ''' <a href="https://www.c-sharpcorner.com/uploadfile/b81385/efficient-string-matching-algorithm-with-use-of-wildcard-characters/"> ''' Efficient String Matching Algorithm with Use of Wildcard Characters</a></summary> Public Module Wildcard ''' <summary>Tests whether specified string can be matched against provided pattern string, where ''' the pattern string may contain wildcards as follows: ? to replace any single character, and * ''' to replace any string.</summary> ''' <param name="input">String which is matched against the pattern.</param> ''' <param name="pattern">Pattern against which string is matched.</param> ''' <returns>true if <paramref name="pattern"/> matches the string <paramref name="input"/>; otherwise false.</returns> Public Function IsMatch(input As String, pattern As String) As Boolean Return IsMatch(input, pattern, "?"c, "*"c) End Function ''' <summary>Tests whether specified string can be matched against provided pattern string. ''' Pattern may contain single- and multiple-replacing wildcard characters.</summary> ''' <param name="input">String which is matched against the pattern.</param> ''' <param name="pattern">Pattern against which string is matched.</param> ''' <param name="singleWildcard">Character which can be used to replace any single character in input string.</param> ''' <param name="multipleWildcard">Character which can be used to replace zero or more characters in input string.</param> ''' <returns>true if <paramref name="pattern"/> matches the string <paramref name="input"/>; otherwise false.</returns> Public Function IsMatch(input As String, pattern As String, singleWildcard As Char, multipleWildcard As Char) As Boolean Dim inputPosStack(((input.Length + 1) * (pattern.Length + 1)) - 1) As Integer ' Stack containing input positions that should be tested for further matching Dim patternPosStack(inputPosStack.Length - 1) As Integer ' Stack containing pattern positions that should be tested for further matching Dim stackPos As Integer = -1 ' Points to last occupied entry in stack; -1 indicates that stack is empty Dim pointTested()() As Boolean = { New Boolean(input.Length) {}, New Boolean(pattern.Length) {} } Dim inputPos As Integer = 0 ' Position in input matched up to the first multiple wildcard in pattern Dim patternPos As Integer = 0 ' Position in pattern matched up to the first multiple wildcard in pattern ' Match beginning of the string until first multiple wildcard in pattern 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) inputPos += 1 patternPos += 1 Loop ' Push this position to stack if it points to end of pattern or to a general wildcard If patternPos = pattern.Length OrElse pattern.Chars(patternPos) = multipleWildcard Then pointTested(0)(inputPos) = True pointTested(1)(patternPos) = True stackPos += 1 inputPosStack(stackPos) = inputPos patternPosStack(stackPos) = patternPos End If Dim matched As Boolean = False ' Repeat matching until either string is matched against the pattern or no more parts remain on stack to test Do While stackPos >= 0 AndAlso Not matched inputPos = inputPosStack(stackPos) ' Pop input and pattern positions from stack patternPos = patternPosStack(stackPos) ' Matching will succeed if rest of the input string matches rest of the pattern stackPos -= 1 If inputPos = input.Length AndAlso patternPos = pattern.Length Then matched = True ' Reached end of both pattern and input string, hence matching is successful Else ' First character in next pattern block is guaranteed to be multiple wildcard ' So skip it and search for all matches in value string until next multiple wildcard character is reached in pattern For curInputStart As Integer = inputPos To input.Length - 1 Dim curInputPos As Integer = curInputStart Dim curPatternPos As Integer = patternPos + 1 If curPatternPos = pattern.Length Then ' Pattern ends with multiple wildcard, hence rest of the input string is matched with that character curInputPos = input.Length Else 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) curInputPos += 1 curPatternPos += 1 Loop End If ' If we have reached next multiple wildcard character in pattern without breaking the matching sequence, then we have another candidate for full match ' This candidate should be pushed to stack for further processing ' 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 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 pointTested(0)(curInputPos) = True pointTested(1)(curPatternPos) = True stackPos += 1 inputPosStack(stackPos) = curInputPos patternPosStack(stackPos) = curPatternPos End If Next curInputStart End If Loop Return matched End Function End Module
|
|
« Última modificación: 19 Abril 2024, 18:53 pm por Eleкtro »
|
En línea
|
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
Librería de Snippets en C/C++
« 1 2 3 4 »
Programación C/C++
|
z3nth10n
|
31
|
25,890
|
2 Agosto 2013, 17:13 pm
por 0xDani
|
|
|
[APORTE] [VBS] Snippets para manipular reglas de bloqueo del firewall de Windows
Scripting
|
Eleкtro
|
1
|
4,084
|
3 Febrero 2014, 20:19 pm
por Eleкtro
|
|
|
Librería de Snippets para Delphi
« 1 2 »
Programación General
|
crack81
|
15
|
21,166
|
25 Marzo 2016, 18:39 pm
por crack81
|
|
|
Una organización en Github para subir, proyectos, snippets y otros?
Sugerencias y dudas sobre el Foro
|
z3nth10n
|
0
|
3,074
|
21 Febrero 2017, 10:47 am
por z3nth10n
|
|
|
índice de la Librería de Snippets para VB.NET !!
.NET (C#, VB.NET, ASP)
|
Eleкtro
|
7
|
6,545
|
4 Julio 2018, 21:35 pm
por Eleкtro
|
|