|
11
|
Foros Generales / Sugerencias y dudas sobre el Foro / [SOLUCIONADO] ¿Cómo desactivo o cambio el corrector ortográfico en el foro?
|
en: 13 Abril 2024, 11:08 am
|
Este problema me sucede desde... no sé, desde hace años, pero no me ha dado por pedir ayuda, hasta ahora. Quien me conozca un poco sabrá que suelo editar mucho mis posts, para corregir faltas, mejorar la redacción, añadir o borrar información (y a veces, cosas que me arrepiento de haber escrito tras haber reflexionado un poco xD), y cosas así. En parte es por que soy (o me considero) perfeccionista, y en parte también es por este problema que voy a explicar, que no me ayuda en nada para darme cuenta de algunos errores ortográficos o algunas teclas que acabo tecleando sin pretender hacerlo... El caso es que, siempre que escribo algo en el foro, se me activa de forma automática el corrector de palabras EN INGLÉS. Y no sé por qué se activa en Inglés, pero creo que no es una configuración de mi navegador (Firefox), por que en el resto de páginas no me sucede esto, solo en el foro. Y entonces, cuando escribo algo, prácticamente todas las palabras en Español me aparecen así como si estuvieran mal escritas: ¿Alguien tiene idea de como puedo hacer para que se active el corrector en Español, o desactivarlo del todo (solo para el foro)?. Gracias.
|
|
|
13
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
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: ' *********************************************************************** ' 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
|
|
|
14
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
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. ''' <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
|
|
|
15
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
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: #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
|
|
|
16
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 11 Abril 2024, 02:14 am
|
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
|
|
|
18
|
Programación / Scripting / [APORTE] [PowerShell] RAR.exe | Test RAR Files
|
en: 5 Abril 2024, 00:39 am
|
El siguiente script, desarrollado en PowerShell y dependiente del programa de terceros WinRAR (rar.exe), sirve para analizar la integridad de los archivos RAR que haya en el directorio donde se ejecute el script. El script genera un archivo con nombre "RAR_Test_Files.log" en el directorio de trabajo, donde se registran los nombres de archivos de los tests fallidos. En este ejemplo: RAR_Test_Files.logFailed test with exit code 3: C:\Nueva carpeta\Stupid Invaders (Spanish) (Disc 1)_128mb.rar Test RAR Files.ps1<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $rarExecutablePath = "${env:ProgramFiles}\WinRAR\rar.exe" $recursiveSearch = $true $logErrorFilePath = "$PSScriptRoot\RAR_Test_Files.log" <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +===================================================+" Write-Host " | |" Write-Host " | This script will use RAR.exe to test each file in |" Write-Host " | the current working directory, and inform about |" Write-Host " | any errors found during the test. |" Write-Host " | |" Write-Host " +===================================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ===========================" -ForegroundColor DarkGray Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor DarkGray Write-Host " Recursive Search...: $recursiveSearch" -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} } function Test-RarFiles { Write-Host "Fetching RAR files, please wait..." -ForegroundColor DarkGray Write-Host "" $rarFiles = $null if ($recursiveSearch) { $rarFiles = Get-ChildItem -LiteralPath "$PSScriptRoot" -Filter "*.rar" -Recurse -File } else { $rarFiles = Get-ChildItem -LiteralPath "$PSScriptRoot" -Filter "*.rar" -File } $rarFileCount = $rarFiles.Count $currentFileCount = 0 If ($rarFileCount -eq 0) {return} $testSuccessCount = 0 $testFailCount = 0 $logStream = [System.IO.StreamWriter]::new($logErrorFilePath, $false ) foreach ($rarFile in $rarFiles) { $currentFileCount +=1 Write-Host "RAR File $currentFileCount of $($rarFileCount):" -ForegroundColor DarkGray $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $rarExecutablePath $psi.Arguments = "t -idcdn `"$($rarFile.FullName)`"" $psi.RedirectStandardOutput = $false $psi.UseShellExecute = $false $psi.CreateNoWindow = $false $process = [System.Diagnostics.Process]::Start($psi) $process.WaitForExit() $exitCode = $process.ExitCode if ($exitCode -eq 0) { Write-Host "RAR process exited with code: $exitCode" -ForegroundColor Green $testSuccessCount +=1 } else { Write-Warning "RAR process exited with code: $exitCode" $logStream.WriteLine("Failed test with exit code $($exitCode): $($rarFile.FullName)") $testFailCount +=1 } Write-Host "" } $logStream.Close() $SuccessPercent = [string]::Format("{0:F0}", ($testSuccessCount / $currentFileCount) * 100) if ($testSuccessCount -eq $currentFileCount) { Write-Host "RAR Tests Successful: $testSuccessCount of $currentFileCount ($SuccessPercent%)" -BackgroundColor Black -ForegroundColor Green } else { Write-Warning "RAR Tests Successful: $testSuccessCount of $currentFileCount ($SuccessPercent%)" } $FailPercent = [string]::Format("{0:F0}", ($testFailCount / $currentFileCount) * 100) if ($testFailCount -eq 0) { Write-Host "RAR Tests Failed....: $testFailCount of $currentFileCount ($FailPercent%)" -BackgroundColor Black -ForegroundColor Green } else { Write-Warning "RAR Tests Failed....: $testFailCount of $currentFileCount ($FailPercent%)" } } function Show-GoodbyeScreen { Write-Host "" Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Test RAR Files - by Elektro" #[System.Console]::SetWindowSize(150, 45) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Test-RarFiles Show-GoodbyeScreen
|
|
|
19
|
Programación / Scripting / Re: [APORTE] [PowerShell] Automated AppX Package Installer
|
en: 5 Abril 2024, 00:13 am
|
Una captura de pantalla: Y una pequeña revisión del código: # --------------------------------------------- # # Automated AppX Package Installer - by Elektro # # --------------------------------------------- # # This script will find any AppX package files within the current directory (without recursion), # print info about the package, print a message in case of the package is already installed, # and install the package in case of it is not installed, handling errors during installation. # --------------------------------------------------------------------- # Takes a string argument that points to an AppX package name or file, # then it uses a regular expression to match the package string pattern # and returns a custom object with the Name, Version, Architecture, # PublisherId and other properties. # # Parameters: # -PackageString: A string that points to the file name # or full path of an AppX package file. # # Returns: # A PSCustomObject object with these properties defined: # [String] Name # [String] Version # [String] Architecture # [String] PublisherId # [String] FullName function Get-AppXPackageInfo { param ( [Parameter(Mandatory=$true)] [string]$PackageString ) #$dirname = [System.IO.Path]::GetDirectoryName($PackageString) #if ([string]::IsNullOrEmpty($dirname)) { # $dirname = $PWD #} $filename = [System.IO.Path]::GetFileName($PackageString) -replace "(?i)\.appxbundle$", "" -replace "(?i)\.msixbundle$", "" -replace "(?i)\.appx$", "" $fileExt = [System.IO.Path]::GetExtension($PackageString) $regex = '^(?<Name>.+?)_(?<Version>.+?)_(?<Architecture>.+?)_(?<chars>~)?_(?<PublisherId>.+)$' $match = $filename -match $regex if (!$match) { throw "Unable to parse the string package: '$PackageString'" } [string]$packageName = $matches['Name'] [string]$packageVersion = $matches['Version'] [string]$packageArchitecture = $matches['Architecture'] [string]$packagePublisherId = $matches['PublisherId'] [string]$chars = $matches['chars'] [string]$packageFullName = "${packageName}_${packageVersion}_${packageArchitecture}_${chars}_${packagePublisherId}$fileExt" #[string]$packageFullPath = [System.IO.Path]::Combine($dirname, "$filename$fileExt") [PSCustomObject]@{ Name = $packageName Version = $packageVersion Architecture = $packageArchitecture PublisherId = $packagePublisherId FullName = $packageFullName #FullPath = $packageFullPath } } # Determines whether an Appx package matching the specified # name, version and architecture is installed in the system. # # Parameters: # -Name........: The package name. # -Version.....: The package version. # -Architecture: The package architecture ("x86", "x64"). # # Returns: # $true if the AppX package is installed in the system, # $false otherwise. function IsAppxPackageInstalled() { param ( [Parameter(Mandatory=$true)] [string]$name, [Parameter(Mandatory=$true)] [string]$version, [Parameter(Mandatory=$true)] [string]$architecture ) if ($architecture -match "neutral") { $architecture = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture } $packages = Get-AppxPackage "$($name)*" -ErrorAction Stop | Where-Object { $_.Name.ToLower() -eq $name.ToLower() -and $_.Version.ToLower() -eq $version.ToLower() -and "$($_.Architecture)".ToLower() -eq $architecture.ToLower() } return ($packages.Count -gt 0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Automated AppX Package Installer - by Elektro" [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } # Hides the progress-bar for 'Add-AppxPackage' cmdlet in this script. # Thanks to @Santiago Squarzon for the tip: https://stackoverflow.com/questions/75716867 # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.3#progresspreference $ProgressPreference = "Ignore" Do { Clear-Host Write-Output "" Write-Output " $($host.ui.RawUI.WindowTitle)" Write-Output " +=====================================================+" Write-Output " | |" Write-Output " | This script will find any AppX package files |" Write-Output " | within the current directory (without recursion), |" Write-Output " | print info about the package, print a message |" Write-Output " | in case of the package is already installed, |" Write-Output " | and install the package in case of it is |" Write-Output " | not installed, handling errors during installation. |" Write-Output " | |" Write-Output " +=====================================================+" Write-Output "" Write-Host " -Continue? (Y/N)" $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} $appxFiles = Get-ChildItem -LiteralPath "$PSScriptRoot" -Filter "*.*" -File | Where-Object { $_.Extension -match "appx" -or $_.Extension -match "appxbundle" -or $_.Extension -match "msixbundle"} if ($appxFiles.Count -eq 0) { Write-Warning "No Appx files were found in the current directory." Write-Host "" $LastExitCode = 2 } else { $appxFiles | ForEach-Object { # The AppX package string. It can be a file name (with or without extension), or a full path. $packageString = $_.FullName $packageInfo = Get-AppXPackageInfo -PackageString $packageString $nameVerArch = "$($packageInfo.Name) v$($packageInfo.Version) ($($packageInfo.Architecture))" Write-Host "Package Info.:" -ForegroundColor Gray Write-Host ($packageInfo | Format-List | Out-String).Trim() -ForegroundColor DarkGray Write-Host "" $isInstalled = IsAppxPackageInstalled -Name $packageInfo.Name -Version $packageInfo.Version -Architecture $packageInfo.Architecture if ($isInstalled) { Write-Warning "Package $nameVerArch is already installed." Write-Warning "Installation is not required. Ignoring..." } else { Write-Host "Package $nameVerArch is ready to install." Write-Host "Installing package..." try { Add-AppxPackage -Path "$($_.FullName)" -ErrorAction Stop Write-Host "Package $nameVerArch has been successfully installed." -BackgroundColor Black -ForegroundColor Green } catch { Write-Host "Error installing package $nameVerArch" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Error -Message ($_.Exception | Format-List * -Force | Out-String) $LastExitCode = 1 Break } } Write-Host "" $LastExitCode = 0 } } Write-Host "Program will terminate now with exit code $LastExitCode. Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Exit($LastExitCode)
|
|
|
20
|
Foros Generales / Foro Libre / Re: Illuminati: He recibido una invitación de membresía.
|
en: 4 Abril 2024, 22:52 pm
|
¿Y nunca habéis recibido una llamada de 'Microsoft' para deciros que vuestro PC está infectado y está infectando a otros usuarios y que deben conectarse a el para solucionar el problema?.
Da la casualidad de que, hace también un par de años, vi en Youtube a otro "reportero" (o creador de contenido) que se dedica a estafar a los estafadores (que les acaban enviando miles de dólares), y a hackearlos (formatearles los discos, sacarles fotos por las webcams, llamarles por teléfono, etc xD), y había un video donde el estafador se hacia pasar por un técnico de un servicio de asistencia no recuerdo si de Microsoft o qué, pero en resumen está relacionado con el tipo de estafa que comentas. El canal de youtube se llama "Scammer Payback", tiene muy buenos videos, el tío suele poner voz como de anciana de 90 años para engañar al estafador. Eso sí, es en Inglés. Hay otro video que se titula " How do Microsoft pop up scammers work (Longest bait-part 1)" y el nombre del canal: "How To Delete", que está más relacionado con este asunto del SCAM de Microsoft. También en Inglés. Para nosotros los informáticos creo que es bueno invertir algo de tiempo en visualizar este tipo de videos para entender como trabajan los scammers y qué tipo de gente y centros organizados hay detrás de este tipo de mafias y estafas. Además, también para echarse unas risas viendo como el estafador es estafado. Como dice el refrán: "Quien roba a un ladrón, tiene cien años de perdón"...
|
|
|
|
|
|
|