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

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 ... 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 [44] 45 46 47 48 49 50 51 52 53 54 55 56 57 58 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 480,234 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #430 en: 14 Septiembre 2014, 11:46 am »

Como añadir una marca de agua en una imagen usando la librería Aspose Imaging ( http://www.aspose.com/.net/imaging-component.aspx ).

Código
  1.    ' Add Watermark
  2.    ' By Elektro
  3.  
  4.    ''' <summary>
  5.    ''' Adds a watermark into an image, at the specified position.
  6.    ''' </summary>
  7.    ''' <param name="img">Indicates the image.</param>
  8.    ''' <param name="text">Indicates the watermark text.</param>
  9.    ''' <param name="fnt">Indicates the watermark text font.</param>
  10.    ''' <param name="color">Indicates the watermark text color.</param>
  11.    ''' <param name="position">Indicates the watermark text position.</param>
  12.    ''' <returns>Aspose.Imaging.Image.</returns>
  13.    Private Function AddWatermark(ByVal img As Aspose.Imaging.Image,
  14.                                  ByVal text As String,
  15.                                  ByVal fnt As Aspose.Imaging.Font,
  16.                                  ByVal color As Aspose.Imaging.Color,
  17.                                  ByVal position As Aspose.Imaging.PointF) As Aspose.Imaging.Image
  18.  
  19.        Using brush As New Aspose.Imaging.Brushes.SolidBrush With {.Color = color, .Opacity = 100.0F}
  20.  
  21.            ' Create and initialize an instance of Graphics class.
  22.            Dim g As New Aspose.Imaging.Graphics(img)
  23.  
  24.            ' Draw a String using the SolidBrush object and Font, at specific Point and with specific format.
  25.            g.DrawString(s:=text, font:=fnt, brush:=brush, point:=position)
  26.  
  27.        End Using
  28.  
  29.        ' Return the modified image.
  30.        Return img
  31.  
  32.    End Function
  33.  
  34.    ''' <summary>
  35.    ''' Adds a watermark into an image, at a prefedined position.
  36.    ''' </summary>
  37.    ''' <param name="img">Indicates the image.</param>
  38.    ''' <param name="text">Indicates the watermark text.</param>
  39.    ''' <param name="fnt">Indicates the watermark text font.</param>
  40.    ''' <param name="color">Indicates the watermark text color.</param>
  41.    ''' <param name="position">Indicates the watermark text position.</param>
  42.    ''' <param name="verticalmargin">Indicates the watermark text vertical margin.</param>
  43.    ''' <param name="horizontalmargin">Indicates the watermark text horizontal margin.</param>
  44.    ''' <returns>Aspose.Imaging.Image.</returns>
  45.    Private Function AddWatermark(ByVal img As Aspose.Imaging.Image,
  46.                                  ByVal text As String,
  47.                                  ByVal fnt As Aspose.Imaging.Font,
  48.                                  ByVal color As Aspose.Imaging.Color,
  49.                                  ByVal position As WatermarkPosition,
  50.                                  Optional ByVal verticalmargin As Single = 0.0F,
  51.                                  Optional ByVal horizontalmargin As Single = 0.0F) As Aspose.Imaging.Image
  52.  
  53.        Dim textformat As New Aspose.Imaging.StringFormat
  54.        Dim textposition As Aspose.Imaging.PointF = Aspose.Imaging.PointF.Empty
  55.        textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces
  56.  
  57.        Select Case position
  58.  
  59.            Case WatermarkPosition.Top ' Note: horizontalmargin value is ignored.
  60.                textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=verticalmargin)
  61.                textformat.Alignment = Aspose.Imaging.StringAlignment.Center
  62.  
  63.            Case WatermarkPosition.TopLeft
  64.                textposition = New Aspose.Imaging.PointF(x:=horizontalmargin, y:=verticalmargin)
  65.                textformat.Alignment = Aspose.Imaging.StringAlignment.Near
  66.  
  67.            Case WatermarkPosition.TopRight
  68.                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
  69.                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
  70.                textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=verticalmargin)
  71.                textformat.Alignment = Aspose.Imaging.StringAlignment.Near
  72.  
  73.            Case WatermarkPosition.Middle ' Note: verticalmargin horizontalmargin and values are ignored.
  74.                textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=(img.Height \ 2))
  75.                textformat.Alignment = Aspose.Imaging.StringAlignment.Center
  76.  
  77.            Case WatermarkPosition.MiddleLeft ' Note: verticalmargin value is ignored.
  78.                textposition = New Aspose.Imaging.PointF(x:=(horizontalmargin), y:=(img.Height \ 2))
  79.                textformat.Alignment = Aspose.Imaging.StringAlignment.Near
  80.  
  81.            Case WatermarkPosition.MiddleRight ' Note: verticalmargin value is ignored.
  82.                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
  83.                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
  84.                textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=(img.Height \ 2))
  85.                textformat.Alignment = Aspose.Imaging.StringAlignment.Near
  86.  
  87.            Case WatermarkPosition.Bottom ' Note: horizontalmargin value is ignored.
  88.                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
  89.                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
  90.                textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=(img.Height - measure.Height - verticalmargin))
  91.                textformat.Alignment = Aspose.Imaging.StringAlignment.Center
  92.  
  93.            Case WatermarkPosition.BottomLeft
  94.                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
  95.                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
  96.                textposition = New Aspose.Imaging.PointF(x:=(horizontalmargin), y:=(img.Height - measure.Height - verticalmargin))
  97.                textformat.Alignment = Aspose.Imaging.StringAlignment.Near
  98.  
  99.            Case WatermarkPosition.BottomRight
  100.                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
  101.                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
  102.                textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=(img.Height - measure.Height - verticalmargin))
  103.                textformat.Alignment = Aspose.Imaging.StringAlignment.Near
  104.  
  105.        End Select
  106.  
  107.        Using brush As New Aspose.Imaging.Brushes.SolidBrush With {.Color = color, .Opacity = 100.0F}
  108.  
  109.            ' Create and initialize an instance of Graphics class.
  110.            Dim g As New Aspose.Imaging.Graphics(img)
  111.  
  112.            ' Draw a String using the SolidBrush object and Font, at specific Point and with specific format.
  113.            g.DrawString(s:=text, font:=fnt, brush:=brush, point:=textposition, format:=textformat)
  114.  
  115.        End Using
  116.  
  117.        textformat.Dispose()
  118.  
  119.        ' Return the modified image.
  120.        Return img
  121.  
  122.    End Function
  123.  
  124.    ''' <summary>
  125.    ''' Specifies a Watermark position
  126.    ''' </summary>
  127.    Public Enum WatermarkPosition As Short
  128.  
  129.        ''' <summary>
  130.        ''' Top position.
  131.        ''' horizontalmargin value is ignored.
  132.        ''' </summary>
  133.        Top = 0S
  134.  
  135.        ''' <summary>
  136.        ''' Top-Left position.
  137.        ''' </summary>
  138.        TopLeft = 1S
  139.  
  140.        ''' <summary>
  141.        ''' Top-Right position.
  142.        ''' </summary>
  143.        TopRight = 2S
  144.  
  145.        ''' <summary>
  146.        ''' Middle-Left position.
  147.        ''' verticalmargin value is ignored.
  148.        ''' </summary>
  149.        MiddleLeft = 3S
  150.  
  151.        ''' <summary>
  152.        ''' Middle position.
  153.        ''' verticalmargin and horizontalmargin values are ignored.
  154.        ''' </summary>
  155.        Middle = 4S
  156.  
  157.        ''' <summary>
  158.        ''' Middle-Right position.
  159.        ''' verticalmargin value is ignored.
  160.        ''' </summary>
  161.        MiddleRight = 5S
  162.  
  163.        ''' <summary>
  164.        ''' Bottom position.
  165.        ''' horizontalmargin value is ignored.
  166.        ''' </summary>
  167.        Bottom = 6S
  168.  
  169.        ''' <summary>
  170.        ''' Bottom-Left position.
  171.        ''' </summary>
  172.        BottomLeft = 7S
  173.  
  174.        ''' <summary>
  175.        ''' Bottom-Right position.
  176.        ''' </summary>
  177.        BottomRight = 8S
  178.  
  179.    End Enum

Ejemplo de uso:

Código
  1.    Private Sub Form1_Load() Handles MyBase.Load
  2.  
  3.        ' Load an image to add a watermark.
  4.        Dim img As Aspose.Imaging.Image = Aspose.Imaging.Image.Load("C:\sample.bmp")
  5.  
  6.        ' Set the watermark text.
  7.        Dim text As String = "ElektroStudios"
  8.  
  9.        ' Set the watermark text color.
  10.        Dim color As Aspose.Imaging.Color = Aspose.Imaging.Color.White
  11.  
  12.        ' Set the watermark text font.
  13.        Dim fnt As New Aspose.Imaging.Font("Lucida Console", 32, FontStyle.Bold)
  14.  
  15.        ' Add the watermark into the image.
  16.        img = Me.AddWatermark(img:=img, text:=text, fnt:=fnt, color:=color, position:=WatermarkPosition.BottomRight)
  17.  
  18.        ' Or...
  19.        ' Dim position As New Aspose.Imaging.PointF(x:=10, y:=10)
  20.        ' img = Me.AddWatermark(img:=img, text:=text, fnt:=fnt, color:=color, position:=position)
  21.  
  22.        ' Save the image to disk.
  23.        img.Save("C:\Watermark.bmp")
  24.  
  25.        ' See the resulting image.
  26.        Process.Start("C:\Watermark.bmp")
  27.        Application.Exit()
  28.  
  29.    End Sub


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #431 en: 18 Septiembre 2014, 21:57 pm »

Un método alternativo (al p/invoking) para detectar un triple-click en WinForms (esto en WPF se puede detectar practicamente en una sola linea, pero en WinForms es más complicado)

Código
  1.    ''' <summary>
  2.    ''' Flag that determines whether the user made a single click.
  3.    ''' </summary>
  4.    Private DidSingleClick As Boolean = False
  5.  
  6.    ''' <summary>
  7.    ''' Flag that determines whether the user made a double click.
  8.    ''' </summary>
  9.    Private DidDoubleClick As Boolean = False
  10.  
  11.    ''' <summary>
  12.    ''' Flag that determines whether the user made a triple click.
  13.    ''' </summary>
  14.    Private DidTripleclick As Boolean = False
  15.  
  16.    ''' <summary>
  17.    ''' Timer that resets the click-count after an inactivity period.
  18.    ''' </summary>
  19.    Private WithEvents ClickInactivity_Timer As New Timer With
  20.    {
  21.        .Interval = SystemInformation.DoubleClickTime,
  22.        .Enabled = False
  23.    }
  24.  
  25.    ''' <summary>
  26.    ''' Handles the MouseClick event of the TextBox1 control.
  27.    ''' </summary>
  28.    ''' <param name="sender">The source of the event.</param>
  29.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  30.    Private Sub TextBox1_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs) _
  31.    Handles TextBox1.MouseClick
  32.  
  33.        If Me.ClickInactivity_Timer.Enabled Then
  34.            Me.ClickInactivity_Timer.Enabled = False
  35.        End If
  36.  
  37.        Me.DidSingleClick = True
  38.  
  39.    End Sub
  40.  
  41.    ''' <summary>
  42.    ''' Handles the MouseDoubleClick event of the TextBox1 control.
  43.    ''' </summary>
  44.    ''' <param name="sender">The source of the event.</param>
  45.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  46.    Private Sub TextBox1_MouseDoubleClick(ByVal sender As Object, ByVal e As MouseEventArgs) _
  47.    Handles TextBox1.MouseDoubleClick
  48.  
  49.        If Me.ClickInactivity_Timer.Enabled Then
  50.            Me.ClickInactivity_Timer.Enabled = False
  51.        End If
  52.  
  53.        Me.DidDoubleClick = True
  54.  
  55.    End Sub
  56.  
  57.    ''' <summary>
  58.    ''' Handles the MouseUp event of the TextBox1 control.
  59.    ''' </summary>
  60.    ''' <param name="sender">The source of the event.</param>
  61.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  62.    Private Sub TextBox1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) _
  63.    Handles TextBox1.MouseUp
  64.  
  65.        If Not Me.ClickInactivity_Timer.Enabled Then
  66.  
  67.            Me.ClickInactivity_Timer.Enabled = True
  68.            Me.ClickInactivity_Timer.Start()
  69.  
  70.        End If
  71.  
  72.    End Sub
  73.  
  74.    ''' <summary>
  75.    ''' Handles the MouseDown event of the TextBox1 control.
  76.    ''' </summary>
  77.    ''' <param name="sender">The source of the event.</param>
  78.    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
  79.    Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
  80.    Handles TextBox1.MouseDown
  81.  
  82.        Me.DidTripleclick = (Me.DidDoubleClick AndAlso Me.DidSingleClick)
  83.  
  84.        If Me.DidTripleclick Then
  85.  
  86.            Me.DidSingleClick = False
  87.            Me.DidDoubleClick = False
  88.            Me.DidTripleclick = False
  89.  
  90.            sender.SelectAll()
  91.  
  92.        End If
  93.  
  94.    End Sub
  95.  
  96.    ''' <summary>
  97.    ''' Handles the Tick event of the ClickInactivity_Timer control.
  98.    ''' </summary>
  99.    ''' <param name="sender">The source of the event.</param>
  100.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  101.    Private Sub ClickInactivity_Timer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
  102.    Handles ClickInactivity_Timer.Tick
  103.  
  104.        Me.DidSingleClick = False
  105.        Me.DidDoubleClick = False
  106.        Me.DidTripleclick = False
  107.  
  108.        sender.Enabled = False
  109.  
  110.    End Sub


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #432 en: 19 Septiembre 2014, 15:02 pm »

WindowSticker
· Adhiere el Form a los bordes de la pantalla al mover la ventana cerca de los bordes.

Ejemplo de uso:

Código
  1. Private WindowSticker As New WindowSticker(ClientForm:=Me) With {.SnapMargin = 35}


Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 09-19-2014
  4. ' ***********************************************************************
  5. ' <copyright file="WindowSticker.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ' Private WindowSticker As New WindowSticker(ClientForm:=Me) With {.SnapMargin = 35}
  13.  
  14. 'Private Sub Form1_Load() Handles MyBase.Shown
  15.  
  16. '    WindowSticker.Dispose()
  17. '    WindowSticker = New WindowSticker(Form2)
  18. '    WindowSticker.ClientForm.Show()
  19.  
  20. 'End Sub
  21.  
  22. #End Region
  23.  
  24. #Region " Imports "
  25.  
  26. Imports System.ComponentModel
  27. Imports System.Runtime.InteropServices
  28.  
  29. #End Region
  30.  
  31. #Region " WindowSticker "
  32.  
  33. ''' <summary>
  34. ''' Sticks a Form to a Desktop border (if the Form is near).
  35. ''' </summary>
  36. Public Class WindowSticker : Inherits NativeWindow : Implements IDisposable
  37.  
  38. #Region " Properties "
  39.  
  40. #Region " Public "
  41.  
  42.    ''' <summary>
  43.    ''' Gets the client form used to stick its borders.
  44.    ''' </summary>
  45.    ''' <value>The client form used to stick its borders.</value>
  46.    Public ReadOnly Property ClientForm As Form
  47.        Get
  48.            Return Me._ClientForm
  49.        End Get
  50.    End Property
  51.    Private WithEvents _ClientForm As Form = Nothing
  52.  
  53.    ''' <summary>
  54.    ''' Gets or sets the snap margin (offset), in pixels.
  55.    ''' (Default value is: 30))
  56.    ''' </summary>
  57.    ''' <value>The snap margin (offset), in pixels.</value>
  58.    Public Property SnapMargin As Integer
  59.        Get
  60.            Return Me._SnapMargin
  61.        End Get
  62.        Set(ByVal value As Integer)
  63.            Me.DisposedCheck()
  64.            Me._SnapMargin = value
  65.        End Set
  66.    End Property
  67.    Private _SnapMargin As Integer = 30I
  68.  
  69. #End Region
  70.  
  71. #Region " Private "
  72.  
  73.    ''' <summary>
  74.    ''' Gets rectangle that contains the size of the current screen.
  75.    ''' </summary>
  76.    ''' <value>The rectangle that contains the size of the current screen.</value>
  77.    Private ReadOnly Property ScreenRect As Rectangle
  78.        Get
  79.            Return Screen.FromControl(Me._ClientForm).Bounds
  80.        End Get
  81.    End Property
  82.  
  83.    ''' <summary>
  84.    ''' Gets the working area of the current screen.
  85.    ''' </summary>
  86.    ''' <value>The working area of the current screen.</value>
  87.    Private ReadOnly Property WorkingArea As Rectangle
  88.        Get
  89.            Return Screen.FromControl(Me._ClientForm).WorkingArea
  90.        End Get
  91.    End Property
  92.  
  93.    ''' <summary>
  94.    ''' Gets the desktop taskbar height (when thet taskbar is horizontal).
  95.    ''' </summary>
  96.    ''' <value>The desktop taskbar height (when thet taskbar is horizontal).</value>
  97.    Private ReadOnly Property TaskbarHeight As Integer
  98.        Get
  99.            Return Me.ScreenRect.Height - Me.WorkingArea.Height
  100.        End Get
  101.    End Property
  102.  
  103. #End Region
  104.  
  105. #End Region
  106.  
  107. #Region " Enumerations "
  108.  
  109.    ''' <summary>
  110.    ''' Windows Message Identifiers.
  111.    ''' </summary>
  112.    <Description("Messages to process in WndProc")>
  113.    Public Enum WindowsMessages As Integer
  114.  
  115.        ''' <summary>
  116.        ''' Sent to a window whose size, position, or place in the Z order is about to change.
  117.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632653%28v=vs.85%29.aspx
  118.        ''' </summary>
  119.        WM_WINDOWPOSCHANGING = &H46I
  120.  
  121.    End Enum
  122.  
  123. #End Region
  124.  
  125. #Region " Structures "
  126.  
  127.    ''' <summary>
  128.    ''' Contains information about the size and position of a window.
  129.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632612%28v=vs.85%29.aspx
  130.    ''' </summary>
  131.    <StructLayout(LayoutKind.Sequential)>
  132.    Public Structure WINDOWPOS
  133.  
  134.        ''' <summary>
  135.        ''' A handle to the window.
  136.        ''' </summary>
  137.        Public hwnd As IntPtr
  138.  
  139.        ''' <summary>
  140.        ''' The position of the window in Z order (front-to-back position).
  141.        ''' This member can be a handle to the window behind which this window is placed,
  142.        ''' or can be one of the special values listed with the 'SetWindowPos' function.
  143.        ''' </summary>
  144.        Public hwndInsertAfter As IntPtr
  145.  
  146.        ''' <summary>
  147.        ''' The position of the left edge of the window.
  148.        ''' </summary>
  149.        Public x As Integer
  150.  
  151.        ''' <summary>
  152.        ''' The position of the top edge of the window.
  153.        ''' </summary>
  154.        Public y As Integer
  155.  
  156.        ''' <summary>
  157.        ''' The window width, in pixels.
  158.        ''' </summary>
  159.        Public width As Integer
  160.  
  161.        ''' <summary>
  162.        ''' The window height, in pixels.
  163.        ''' </summary>
  164.        Public height As Integer
  165.  
  166.        ''' <summary>
  167.        ''' Flag containing the window position.
  168.        ''' </summary>
  169.        Public flags As Integer
  170.  
  171.    End Structure
  172.  
  173. #End Region
  174.  
  175. #Region " Constructor "
  176.  
  177.    ''' <summary>
  178.    ''' Initializes a new instance of WindowSticker class.
  179.    ''' </summary>
  180.    ''' <param name="ClientForm">The client form to assign this NativeWindow.</param>
  181.    Public Sub New(ByVal ClientForm As Form)
  182.  
  183.        ' Assign the Formulary.
  184.        Me._ClientForm = ClientForm
  185.  
  186.    End Sub
  187.  
  188.    ''' <summary>
  189.    ''' Prevents a default instance of the <see cref="WindowSticker"/> class from being created.
  190.    ''' </summary>
  191.    Private Sub New()
  192.    End Sub
  193.  
  194. #End Region
  195.  
  196. #Region " Event Handlers "
  197.  
  198.    ''' <summary>
  199.    ''' Assign the handle of the target Form to this NativeWindow,
  200.    ''' necessary to override target Form's WndProc.
  201.    ''' </summary>
  202.    Private Sub SetFormHandle() Handles _ClientForm.HandleCreated, _ClientForm.Load, _ClientForm.Shown
  203.  
  204.        If (Me._ClientForm IsNot Nothing) AndAlso (Not MyBase.Handle.Equals(Me._ClientForm.Handle)) Then
  205.  
  206.            MyBase.AssignHandle(Me._ClientForm.Handle)
  207.  
  208.        End If
  209.  
  210.    End Sub
  211.  
  212.    ''' <summary>
  213.    ''' Releases the Handle.
  214.    ''' </summary>
  215.    Private Sub OnHandleDestroyed() Handles _ClientForm.HandleDestroyed
  216.  
  217.        MyBase.ReleaseHandle()
  218.  
  219.    End Sub
  220.  
  221. #End Region
  222.  
  223. #Region " WndProc "
  224.  
  225.    ''' <summary>
  226.    ''' Invokes the default window procedure associated with this window to process messages.
  227.    ''' </summary>
  228.    ''' <param name="m">
  229.    ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
  230.    ''' </param>
  231.    Protected Overrides Sub WndProc(ByRef m As Message)
  232.  
  233.        If (Me._ClientForm IsNot Nothing) AndAlso (m.Msg = WindowsMessages.WM_WINDOWPOSCHANGING) Then
  234.  
  235.            Me.SnapToDesktopBorder(ClientForm:=Me._ClientForm, Handle:=m.LParam, widthAdjustment:=0)
  236.  
  237.        End If
  238.  
  239.        MyBase.WndProc(m)
  240.  
  241.    End Sub
  242.  
  243. #End Region
  244.  
  245. #Region " Private Methods "
  246.  
  247.    ''' <summary>
  248.    ''' Sticks a Form to a desktop border (it its near).
  249.    ''' </summary>
  250.    ''' <param name="ClientForm">The client form used to stick its borders.</param>
  251.    ''' <param name="Handle">A pointer to a 'WINDOWPOS' structure that contains information about the window's new size and position.</param>
  252.    ''' <param name="widthAdjustment">The border width adjustment.</param>
  253.    Private Sub SnapToDesktopBorder(ByVal ClientForm As Form,
  254.                                    ByVal Handle As IntPtr,
  255.                                    Optional ByVal widthAdjustment As Integer = 0I)
  256.  
  257.        Dim newPosition As WINDOWPOS = CType(Marshal.PtrToStructure(Handle, GetType(WINDOWPOS)), WINDOWPOS)
  258.  
  259.        If (newPosition.y = 0) OrElse (newPosition.x = 0) Then
  260.            ' Nothing to do.
  261.            Exit Sub
  262.        End If
  263.  
  264.        ' Top border (check if taskbar is on top or bottom via WorkingRect.Y)
  265.        If (newPosition.y >= -SnapMargin AndAlso (Me.WorkingArea.Y > 0 AndAlso newPosition.y <= (Me.TaskbarHeight + Me.SnapMargin))) _
  266.        OrElse (Me.WorkingArea.Y <= 0 AndAlso newPosition.y <= (SnapMargin)) Then
  267.  
  268.            If Me.TaskbarHeight > 0 Then
  269.                ' Horizontal Taskbar
  270.                newPosition.y = Me.WorkingArea.Y
  271.            Else
  272.                ' Vertical Taskbar
  273.                newPosition.y = 0
  274.            End If
  275.  
  276.        End If
  277.  
  278.        ' Left border
  279.        If (newPosition.x >= Me.WorkingArea.X - Me.SnapMargin) _
  280.        AndAlso (newPosition.x <= Me.WorkingArea.X + Me.SnapMargin) Then
  281.  
  282.            newPosition.x = Me.WorkingArea.X
  283.  
  284.        End If
  285.  
  286.        ' Right border.
  287.        If (newPosition.x + Me._ClientForm.Width <= Me.WorkingArea.Right + Me.SnapMargin) _
  288.        AndAlso (newPosition.x + Me._ClientForm.Width >= Me.WorkingArea.Right - Me.SnapMargin) Then
  289.  
  290.            newPosition.x = (Me.WorkingArea.Right - Me._ClientForm.Width)
  291.  
  292.        End If
  293.  
  294.        ' Bottom border.
  295.        If (newPosition.y + Me._ClientForm.Height <= Me.WorkingArea.Bottom + Me.SnapMargin) _
  296.        AndAlso (newPosition.y + Me._ClientForm.Height >= Me.WorkingArea.Bottom - Me.SnapMargin) Then
  297.  
  298.            newPosition.y = (Me.WorkingArea.Bottom - Me._ClientForm.Height)
  299.  
  300.        End If
  301.  
  302.        ' Marshal it back.
  303.        Marshal.StructureToPtr([structure]:=newPosition, ptr:=Handle, fDeleteOld:=True)
  304.  
  305.    End Sub
  306.  
  307. #End Region
  308.  
  309. #Region " Hidden Methods "
  310.  
  311.    ''' <summary>
  312.    ''' Determines whether the specified System.Object instances are the same instance.
  313.    ''' </summary>
  314.    <EditorBrowsable(EditorBrowsableState.Never)>
  315.    Private Shadows Sub ReferenceEquals()
  316.    End Sub
  317.  
  318.    ''' <summary>
  319.    ''' Assigns a handle to this window.
  320.    ''' </summary>
  321.    <EditorBrowsable(EditorBrowsableState.Never)>
  322.    Public Shadows Sub AssignHandle()
  323.    End Sub
  324.  
  325.    ''' <summary>
  326.    ''' Creates a window and its handle with the specified creation parameters.
  327.    ''' </summary>
  328.    <EditorBrowsable(EditorBrowsableState.Never)>
  329.    Public Shadows Sub CreateHandle()
  330.    End Sub
  331.  
  332.    ''' <summary>
  333.    ''' Destroys the window and its handle.
  334.    ''' </summary>
  335.    <EditorBrowsable(EditorBrowsableState.Never)>
  336.    Public Shadows Sub DestroyHandle()
  337.    End Sub
  338.  
  339.    ''' <summary>
  340.    ''' Releases the handle associated with this window.
  341.    ''' </summary>
  342.    <EditorBrowsable(EditorBrowsableState.Never)>
  343.    Public Shadows Sub ReleaseHandle()
  344.    End Sub
  345.  
  346.    ''' <summary>
  347.    ''' Retrieves the window associated with the specified handle.
  348.    ''' </summary>
  349.    <EditorBrowsable(EditorBrowsableState.Never)>
  350.    Private Shadows Sub FromHandle()
  351.    End Sub
  352.  
  353.    ''' <summary>
  354.    ''' Serves as a hash function for a particular type.
  355.    ''' </summary>
  356.    <EditorBrowsable(EditorBrowsableState.Never)>
  357.    Public Shadows Sub GetHashCode()
  358.    End Sub
  359.  
  360.    ''' <summary>
  361.    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
  362.    ''' </summary>
  363.    <EditorBrowsable(EditorBrowsableState.Never)>
  364.    Public Shadows Function GetLifeTimeService()
  365.        Return Nothing
  366.    End Function
  367.  
  368.    ''' <summary>
  369.    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
  370.    ''' </summary>
  371.    <EditorBrowsable(EditorBrowsableState.Never)>
  372.    Public Shadows Function InitializeLifeTimeService()
  373.        Return Nothing
  374.    End Function
  375.  
  376.    ''' <summary>
  377.    ''' Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
  378.    ''' </summary>
  379.    <EditorBrowsable(EditorBrowsableState.Never)>
  380.    Public Shadows Function CreateObjRef()
  381.        Return Nothing
  382.    End Function
  383.  
  384.    ''' <summary>
  385.    ''' Determines whether the specified System.Object instances are considered equal.
  386.    ''' </summary>
  387.    <EditorBrowsable(EditorBrowsableState.Never)>
  388.    Public Shadows Sub Equals()
  389.    End Sub
  390.  
  391.    ''' <summary>
  392.    ''' Returns a String that represents the current object.
  393.    ''' </summary>
  394.    <EditorBrowsable(EditorBrowsableState.Never)>
  395.    Public Shadows Sub ToString()
  396.    End Sub
  397.  
  398.    ''' <summary>
  399.    ''' Invokes the default window procedure associated with this window.
  400.    ''' </summary>
  401.    <EditorBrowsable(EditorBrowsableState.Never)>
  402.    Public Shadows Sub DefWndProc()
  403.    End Sub
  404.  
  405. #End Region
  406.  
  407. #Region " IDisposable "
  408.  
  409.    ''' <summary>
  410.    ''' To detect redundant calls when disposing.
  411.    ''' </summary>
  412.    Private IsDisposed As Boolean = False
  413.  
  414.    ''' <summary>
  415.    ''' Prevent calls to methods after disposing.
  416.    ''' </summary>
  417.    ''' <exception cref="System.ObjectDisposedException"></exception>
  418.    Private Sub DisposedCheck()
  419.  
  420.        If Me.IsDisposed Then
  421.            Throw New ObjectDisposedException(Me.GetType().FullName)
  422.        End If
  423.  
  424.    End Sub
  425.  
  426.    ''' <summary>
  427.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  428.    ''' </summary>
  429.    Public Sub Dispose() Implements IDisposable.Dispose
  430.        Dispose(True)
  431.        GC.SuppressFinalize(Me)
  432.    End Sub
  433.  
  434.    ''' <summary>
  435.    ''' Releases unmanaged and - optionally - managed resources.
  436.    ''' </summary>
  437.    ''' <param name="IsDisposing">
  438.    ''' <c>true</c> to release both managed and unmanaged resources;
  439.    ''' <c>false</c> to release only unmanaged resources.
  440.    ''' </param>
  441.    Protected Sub Dispose(ByVal IsDisposing As Boolean)
  442.  
  443.        If Not Me.IsDisposed Then
  444.  
  445.            If IsDisposing Then
  446.                Me._ClientForm = Nothing
  447.                MyBase.ReleaseHandle()
  448.                MyBase.DestroyHandle()
  449.            End If
  450.  
  451.        End If
  452.  
  453.        Me.IsDisposed = True
  454.  
  455.    End Sub
  456.  
  457. #End Region
  458.  
  459. End Class
  460.  
  461. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #433 en: 28 Septiembre 2014, 06:14 am »

Ejecuta un applet del panel de control

ejemplo de uso:
Código
  1. ControlPanelLauncher.Run(ControlPanelLauncher.Applets.SystemProperties)



Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 09-28-2014
  4. ' ***********************************************************************
  5. ' <copyright file="ControlPanelLauncher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ' ControlPanelLauncher.Run()
  13. ' ControlPanelLauncher.RunApplet(ControlPanelLauncher.Applets.SystemProperties)
  14.  
  15. #End Region
  16.  
  17. ''' <summary>
  18. ''' Runs a Windows Control Panel Applet.
  19. ''' Unofficial documentation: http://pcsupport.about.com/od/tipstricks/a/control-panel-command-line.htm
  20. ''' </summary>
  21. Public Class ControlPanelLauncher
  22.  
  23. #Region " Constants/Readonly "
  24.  
  25.    ''' <summary>
  26.    ''' The ControlPanel process location (control.exe)
  27.    ''' </summary>
  28.    Private Shared ReadOnly ControlProcess As String =
  29.        IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "control.exe")
  30.  
  31. #End Region
  32.  
  33. #Region " Enumerations "
  34.  
  35.    ''' <summary>
  36.    ''' Specifies a Control Panel Applet.
  37.    ''' </summary>
  38.    Public Enum Applets As Integer
  39.  
  40.        ''' <summary>
  41.        ''' Action Center
  42.        ''' </summary>
  43.        ActionCenter
  44.  
  45.        ''' <summary>
  46.        ''' Add Hardware
  47.        ''' </summary>
  48.        AddHardware
  49.  
  50.        ''' <summary>
  51.        ''' Administrative Tools
  52.        ''' </summary>
  53.        AdministrativeTools
  54.  
  55.        ''' <summary>
  56.        ''' AutoPlay
  57.        ''' </summary>
  58.        AutoPlay
  59.  
  60.        ''' <summary>
  61.        ''' Backup And Restore
  62.        ''' </summary>
  63.        BackupAndRestore
  64.  
  65.        ''' <summary>
  66.        ''' Biometric Devices
  67.        ''' </summary>
  68.        BiometricDevices
  69.  
  70.        ''' <summary>
  71.        ''' BitLocker Drive Encryption
  72.        ''' </summary>
  73.        BitLockerDriveEncryption
  74.  
  75.        ''' <summary>
  76.        ''' Bluetooth Devices
  77.        ''' </summary>
  78.        BluetoothDevices
  79.  
  80.        ''' <summary>
  81.        ''' Color Management
  82.        ''' </summary>
  83.        ColorManagement
  84.  
  85.        ''' <summary>
  86.        ''' Credential Manager
  87.        ''' </summary>
  88.        CredentialManager
  89.  
  90.        ''' <summary>
  91.        ''' Date And Time
  92.        ''' </summary>
  93.        DateAndTime
  94.  
  95.        ''' <summary>
  96.        ''' Default Location
  97.        ''' </summary>
  98.        DefaultLocation
  99.  
  100.        ''' <summary>
  101.        ''' Default Programs
  102.        ''' </summary>
  103.        DefaultPrograms
  104.  
  105.        ''' <summary>
  106.        ''' Desktop Gadgets
  107.        ''' </summary>
  108.        DesktopGadgets
  109.  
  110.        ''' <summary>
  111.        ''' Device Manager
  112.        ''' </summary>
  113.        DeviceManager
  114.  
  115.        ''' <summary>
  116.        ''' Devices And Printers
  117.        ''' </summary>
  118.        DevicesAndPrinters
  119.  
  120.        ''' <summary>
  121.        ''' Display
  122.        ''' </summary>
  123.        Display
  124.  
  125.        ''' <summary>
  126.        ''' EaseOfAccess Center
  127.        ''' </summary>
  128.        EaseOfAccessCenter
  129.  
  130.        ''' <summary>
  131.        ''' Family Safety
  132.        ''' </summary>
  133.        FamilySafety
  134.  
  135.        ''' <summary>
  136.        ''' File History
  137.        ''' </summary>
  138.        FileHistory
  139.  
  140.        ''' <summary>
  141.        ''' FlashPlayer Settings Manager
  142.        ''' </summary>
  143.        FlashPlayerSettingsManager
  144.  
  145.        ''' <summary>
  146.        ''' Folder Options
  147.        ''' </summary>
  148.        FolderOptions
  149.  
  150.        ''' <summary>
  151.        ''' Fonts
  152.        ''' </summary>
  153.        Fonts
  154.  
  155.        ''' <summary>
  156.        ''' Game Controllers
  157.        ''' </summary>
  158.        GameControllers
  159.  
  160.        ''' <summary>
  161.        ''' Get Programs
  162.        ''' </summary>
  163.        GetPrograms
  164.  
  165.        ''' <summary>
  166.        ''' Getting Started
  167.        ''' </summary>
  168.        GettingStarted
  169.  
  170.        ''' <summary>
  171.        ''' Home Group
  172.        ''' </summary>
  173.        HomeGroup
  174.  
  175.        ''' <summary>
  176.        ''' Indexing Options
  177.        ''' </summary>
  178.        IndexingOptions
  179.  
  180.        ''' <summary>
  181.        ''' Infrared
  182.        ''' </summary>
  183.        Infrared
  184.  
  185.        ''' <summary>
  186.        ''' Internet Options
  187.        ''' </summary>
  188.        InternetOptions
  189.  
  190.        ''' <summary>
  191.        ''' iSCSI Initiator
  192.        ''' </summary>
  193.        iSCSIInitiator
  194.  
  195.        ''' <summary>
  196.        ''' Keyboard
  197.        ''' </summary>
  198.        Keyboard
  199.  
  200.        ''' <summary>
  201.        ''' Language
  202.        ''' </summary>
  203.        Language
  204.  
  205.        ''' <summary>
  206.        ''' Location And Other Sensors
  207.        ''' </summary>
  208.        LocationAndOtherSensors
  209.  
  210.        ''' <summary>
  211.        ''' Mouse
  212.        ''' </summary>
  213.        Mouse
  214.  
  215.        ''' <summary>
  216.        ''' Network And Sharing Center
  217.        ''' </summary>
  218.        NetworkAndSharingCenter
  219.  
  220.        ''' <summary>
  221.        ''' Network Connections
  222.        ''' </summary>
  223.        NetworkConnections
  224.  
  225.        ''' <summary>
  226.        ''' Network Setup Wizard
  227.        ''' </summary>
  228.        NetworkSetupWizard
  229.  
  230.        ''' <summary>
  231.        ''' Notification Area Icons
  232.        ''' </summary>
  233.        NotificationAreaIcons
  234.  
  235.        ''' <summary>
  236.        ''' Offline Files
  237.        ''' </summary>
  238.        OfflineFiles
  239.  
  240.        ''' <summary>
  241.        ''' Parental Controls
  242.        ''' </summary>
  243.        ParentalControls
  244.  
  245.        ''' <summary>
  246.        ''' Pen And Input Devices
  247.        ''' </summary>
  248.        PenAndInputDevices
  249.  
  250.        ''' <summary>
  251.        ''' Pen And Touch
  252.        ''' </summary>
  253.        PenAndTouch
  254.  
  255.        ''' <summary>
  256.        ''' People Near Me
  257.        ''' </summary>
  258.        PeopleNearMe
  259.  
  260.        ''' <summary>
  261.        ''' Performance Information And Tools
  262.        ''' </summary>
  263.        PerformanceInformationAndTools
  264.  
  265.        ''' <summary>
  266.        ''' Personalization
  267.        ''' </summary>
  268.        Personalization
  269.  
  270.        ''' <summary>
  271.        ''' Phone And Modem Options
  272.        ''' </summary>
  273.        PhoneAndModemOptions
  274.  
  275.        ''' <summary>
  276.        ''' Phone And Modem
  277.        ''' </summary>
  278.        PhoneAndModem
  279.  
  280.        ''' <summary>
  281.        ''' Power Options
  282.        ''' </summary>
  283.        PowerOptions
  284.  
  285.        ''' <summary>
  286.        ''' Printers And Faxes
  287.        ''' </summary>
  288.        PrintersAndFaxes
  289.  
  290.        ''' <summary>
  291.        ''' Problem Reports And Solutions
  292.        ''' </summary>
  293.        ProblemReportsAndSolutions
  294.  
  295.        ''' <summary>
  296.        ''' Programs And Features
  297.        ''' </summary>
  298.        ProgramsAndFeatures
  299.  
  300.        ''' <summary>
  301.        ''' Recovery
  302.        ''' </summary>
  303.        Recovery
  304.  
  305.        ''' <summary>
  306.        ''' Region And Language
  307.        ''' </summary>
  308.        RegionAndLanguage
  309.  
  310.        ''' <summary>
  311.        ''' Regional And Language Options
  312.        ''' </summary>
  313.        RegionalAndLanguageOptions
  314.  
  315.        ''' <summary>
  316.        ''' Remote App And Desktop Connections
  317.        ''' </summary>
  318.        RemoteAppAndDesktopConnections
  319.  
  320.        ''' <summary>
  321.        ''' Scanners And Cameras
  322.        ''' </summary>
  323.        ScannersAndCameras
  324.  
  325.        ''' <summary>
  326.        ''' Screen Resolution
  327.        ''' </summary>
  328.        ScreenResolution
  329.  
  330.        ''' <summary>
  331.        ''' Security Center
  332.        ''' </summary>
  333.        SecurityCenter
  334.  
  335.        ''' <summary>
  336.        ''' Sound
  337.        ''' </summary>
  338.        Sound
  339.  
  340.        ''' <summary>
  341.        ''' Speech Recognition Options
  342.        ''' </summary>
  343.        SpeechRecognitionOptions
  344.  
  345.        ''' <summary>
  346.        ''' Speech Recognition
  347.        ''' </summary>
  348.        SpeechRecognition
  349.  
  350.        ''' <summary>
  351.        ''' Storage Spaces
  352.        ''' </summary>
  353.        StorageSpaces
  354.  
  355.        ''' <summary>
  356.        ''' Sync Center
  357.        ''' </summary>
  358.        SyncCenter
  359.  
  360.        ''' <summary>
  361.        ''' System
  362.        ''' </summary>
  363.        System
  364.  
  365.        ''' <summary>
  366.        ''' System Properties
  367.        ''' </summary>
  368.        SystemProperties
  369.  
  370.        ''' <summary>
  371.        ''' TabletPC Settings
  372.        ''' </summary>
  373.        TabletPCSettings
  374.  
  375.        ''' <summary>
  376.        ''' Task Scheduler
  377.        ''' </summary>
  378.        TaskScheduler
  379.  
  380.        ''' <summary>
  381.        ''' Taskbar
  382.        ''' </summary>
  383.        Taskbar
  384.  
  385.        ''' <summary>
  386.        ''' Taskbar And StartMenu
  387.        ''' </summary>
  388.        TaskbarAndStartMenu
  389.  
  390.        ''' <summary>
  391.        ''' Text To Speech
  392.        ''' </summary>
  393.        TextToSpeech
  394.  
  395.        ''' <summary>
  396.        ''' Troubleshooting
  397.        ''' </summary>
  398.        Troubleshooting
  399.  
  400.        ''' <summary>
  401.        ''' User Accounts
  402.        ''' </summary>
  403.        UserAccounts
  404.  
  405.        ''' <summary>
  406.        ''' Welcome Center
  407.        ''' </summary>
  408.        WelcomeCenter
  409.  
  410.        ''' <summary>
  411.        ''' Windows Anytime Upgrade
  412.        ''' </summary>
  413.        WindowsAnytimeUpgrade
  414.  
  415.        ''' <summary>
  416.        ''' Windows CardSpace
  417.        ''' </summary>
  418.        WindowsCardSpace
  419.  
  420.        ''' <summary>
  421.        ''' Windows Defender
  422.        ''' </summary>
  423.        WindowsDefender
  424.  
  425.        ''' <summary>
  426.        ''' Windows Firewall
  427.        ''' </summary>
  428.        WindowsFirewall
  429.  
  430.        ''' <summary>
  431.        ''' Windows Marketplace
  432.        ''' </summary>
  433.        WindowsMarketplace
  434.  
  435.        ''' <summary>
  436.        ''' Windows Mobility Center
  437.        ''' </summary>
  438.        WindowsMobilityCenter
  439.  
  440.        ''' <summary>
  441.        ''' Windows Sidebar Properties
  442.        ''' </summary>
  443.        WindowsSidebarProperties
  444.  
  445.        ''' <summary>
  446.        ''' Windows SideShow
  447.        ''' </summary>
  448.        WindowsSideShow
  449.  
  450.        ''' <summary>
  451.        ''' Windows Update
  452.        ''' </summary>
  453.        WindowsUpdate
  454.  
  455.    End Enum
  456.  
  457. #End Region
  458.  
  459. #Region " Public Methods "
  460.  
  461.    ''' <summary>
  462.    ''' Runs the Control Panel.
  463.    ''' </summary>
  464.    Public Shared Sub Run()
  465.  
  466.        Process.Start(ControlProcess)
  467.  
  468.    End Sub
  469.  
  470.    ''' <summary>
  471.    ''' Runs a Control Panel Applet.
  472.    ''' </summary>
  473.    ''' <param name="Applet">The applet.</param>
  474.    Public Shared Sub RunApplet(ByVal Applet As Applets)
  475.  
  476.        Select Case Applet
  477.  
  478.            Case Applets.ActionCenter
  479.                Process.Start(ControlProcess, "/name Microsoft.ActionCenter")
  480.  
  481.            Case Applets.AddHardware
  482.                Process.Start(ControlProcess, "/name Microsoft.AddHardware")
  483.  
  484.            Case Applets.AdministrativeTools
  485.                Process.Start(ControlProcess, "/name Microsoft.AdministrativeTools")
  486.  
  487.            Case Applets.AutoPlay
  488.                Process.Start(ControlProcess, "/name Microsoft.AutoPlay")
  489.  
  490.            Case Applets.BackupAndRestore
  491.                Process.Start(ControlProcess, "/name Microsoft.BackupAndRestore")
  492.  
  493.            Case Applets.BiometricDevices
  494.                Process.Start(ControlProcess, "/name Microsoft.BiometricDevices")
  495.  
  496.            Case Applets.BitLockerDriveEncryption
  497.                Process.Start(ControlProcess, "/name Microsoft.BitLockerDriveEncryption")
  498.  
  499.            Case Applets.BluetoothDevices
  500.                Process.Start(ControlProcess, "/name Microsoft.BluetoothDevices")
  501.  
  502.            Case Applets.ColorManagement
  503.                Process.Start(ControlProcess, "/name Microsoft.ColorManagement")
  504.  
  505.            Case Applets.CredentialManager
  506.                Process.Start(ControlProcess, "/name Microsoft.CredentialManager")
  507.  
  508.            Case Applets.DateAndTime
  509.                Process.Start(ControlProcess, "/name Microsoft.DateAndTime")
  510.  
  511.            Case Applets.DefaultLocation
  512.                Process.Start(ControlProcess, "/name Microsoft.DefaultLocation")
  513.  
  514.            Case Applets.DefaultPrograms
  515.                Process.Start(ControlProcess, "/name Microsoft.DefaultPrograms")
  516.  
  517.            Case Applets.DesktopGadgets
  518.                Process.Start(ControlProcess, "/name Microsoft.DesktopGadgets")
  519.  
  520.            Case Applets.DeviceManager
  521.                Process.Start(ControlProcess, "/name Microsoft.DeviceManager")
  522.  
  523.            Case Applets.DevicesAndPrinters
  524.                Process.Start(ControlProcess, "/name Microsoft.DevicesAndPrinters")
  525.  
  526.            Case Applets.Display
  527.                Process.Start(ControlProcess, "/name Microsoft.Display")
  528.  
  529.            Case Applets.EaseOfAccessCenter
  530.                Process.Start(ControlProcess, "/name Microsoft.EaseOfAccessCenter")
  531.  
  532.            Case Applets.FamilySafety
  533.                Process.Start(ControlProcess, "/name Microsoft.ParentalControls")
  534.  
  535.            Case Applets.FileHistory
  536.                Process.Start(ControlProcess, "/name Microsoft.FileHistory")
  537.  
  538.            Case Applets.FlashPlayerSettingsManager
  539.                Process.Start(ControlProcess, "flashplayercplapp.cpl")
  540.  
  541.            Case Applets.FolderOptions
  542.                Process.Start(ControlProcess, "/name Microsoft.FolderOptions")
  543.  
  544.            Case Applets.Fonts
  545.                Process.Start(ControlProcess, "/name Microsoft.Fonts")
  546.  
  547.            Case Applets.GameControllers
  548.                Process.Start(ControlProcess, "/name Microsoft.GameControllers")
  549.  
  550.            Case Applets.GetPrograms
  551.                Process.Start(ControlProcess, "/name Microsoft.GetPrograms")
  552.  
  553.            Case Applets.GettingStarted
  554.                Process.Start(ControlProcess, "/name Microsoft.GettingStarted")
  555.  
  556.            Case Applets.HomeGroup
  557.                Process.Start(ControlProcess, "/name Microsoft.HomeGroup")
  558.  
  559.            Case Applets.IndexingOptions
  560.                Process.Start(ControlProcess, "/name Microsoft.IndexingOptions")
  561.  
  562.            Case Applets.Infrared
  563.                Process.Start(ControlProcess, "/name Microsoft.Infrared")
  564.  
  565.            Case Applets.InternetOptions
  566.                Process.Start(ControlProcess, "/name Microsoft.InternetOptions")
  567.  
  568.            Case Applets.iSCSIInitiator
  569.                Process.Start(ControlProcess, "/name Microsoft.iSCSIInitiator")
  570.  
  571.            Case Applets.Keyboard
  572.                Process.Start(ControlProcess, "/name Microsoft.Keyboard")
  573.  
  574.            Case Applets.Language
  575.                Process.Start(ControlProcess, "/name Microsoft.Language")
  576.  
  577.            Case Applets.LocationAndOtherSensors
  578.                Process.Start(ControlProcess, "/name Microsoft.LocationAndOtherSensors")
  579.  
  580.            Case Applets.Mouse
  581.                Process.Start(ControlProcess, "/name Microsoft.Mouse")
  582.  
  583.            Case Applets.NetworkAndSharingCenter
  584.                Process.Start(ControlProcess, "/name Microsoft.NetworkAndSharingCenter")
  585.  
  586.            Case Applets.NetworkConnections
  587.                Process.Start(ControlProcess, "ncpa.cpl")
  588.  
  589.            Case Applets.NetworkSetupWizard
  590.                Process.Start(ControlProcess, "netsetup.cpl")
  591.  
  592.            Case Applets.NotificationAreaIcons
  593.                Process.Start(ControlProcess, "/name Microsoft.NotificationAreaIcons")
  594.  
  595.            Case Applets.OfflineFiles
  596.                Process.Start(ControlProcess, "/name Microsoft.OfflineFiles")
  597.  
  598.            Case Applets.ParentalControls
  599.                Process.Start(ControlProcess, "/name Microsoft.ParentalControls")
  600.  
  601.            Case Applets.PenAndInputDevices
  602.                Process.Start(ControlProcess, "/name Microsoft.PenAndInputDevices")
  603.  
  604.            Case Applets.PenAndTouch
  605.                Process.Start(ControlProcess, "/name Microsoft.PenAndTouch")
  606.  
  607.            Case Applets.PeopleNearMe
  608.                Process.Start(ControlProcess, "/name Microsoft.PeopleNearMe")
  609.  
  610.            Case Applets.PerformanceInformationAndTools
  611.                Process.Start(ControlProcess, "/name Microsoft.PerformanceInformationAndTools")
  612.  
  613.            Case Applets.Personalization
  614.                Process.Start(ControlProcess, "/name Microsoft.Personalization")
  615.  
  616.            Case Applets.PhoneAndModemOptions
  617.                Process.Start(ControlProcess, "/name Microsoft.PhoneAndModemOptions")
  618.  
  619.            Case Applets.PhoneAndModem
  620.                Process.Start(ControlProcess, "/name Microsoft.PhoneAndModem")
  621.  
  622.            Case Applets.PowerOptions
  623.                Process.Start(ControlProcess, "/name Microsoft.PowerOptions")
  624.  
  625.            Case Applets.PrintersAndFaxes
  626.                Process.Start(ControlProcess, "/name Microsoft.Printers")
  627.  
  628.            Case Applets.ProblemReportsAndSolutions
  629.                Process.Start(ControlProcess, "/name Microsoft.ProblemReportsAndSolutions")
  630.  
  631.            Case Applets.ProgramsAndFeatures
  632.                Process.Start(ControlProcess, "/name Microsoft.ProgramsAndFeatures")
  633.  
  634.            Case Applets.Recovery
  635.                Process.Start(ControlProcess, "/name Microsoft.Recovery")
  636.  
  637.            Case Applets.RegionAndLanguage
  638.                Process.Start(ControlProcess, "/name Microsoft.RegionAndLanguage")
  639.  
  640.            Case Applets.RegionalAndLanguageOptions
  641.                Process.Start(ControlProcess, "/name Microsoft.RegionalAndLanguageOptions")
  642.  
  643.            Case Applets.RemoteAppAndDesktopConnections
  644.                Process.Start(ControlProcess, "/name Microsoft.RemoteAppAndDesktopConnections")
  645.  
  646.            Case Applets.ScannersAndCameras
  647.                Process.Start(ControlProcess, "/name Microsoft.ScannersAndCameras")
  648.  
  649.            Case Applets.ScreenResolution
  650.                Process.Start(ControlProcess, "desk.cpl")
  651.  
  652.            Case Applets.SecurityCenter
  653.                Process.Start(ControlProcess, "/name Microsoft.SecurityCenter")
  654.  
  655.            Case Applets.Sound
  656.                Process.Start(ControlProcess, "/name Microsoft.Sound")
  657.  
  658.            Case Applets.SpeechRecognitionOptions
  659.                Process.Start(ControlProcess, "/name Microsoft.SpeechRecognitionOptions")
  660.  
  661.            Case Applets.SpeechRecognition
  662.                Process.Start(ControlProcess, "/name Microsoft.SpeechRecognition")
  663.  
  664.            Case Applets.StorageSpaces
  665.                Process.Start(ControlProcess, "/name Microsoft.StorageSpaces")
  666.  
  667.            Case Applets.SyncCenter
  668.                Process.Start(ControlProcess, "/name Microsoft.SyncCenter")
  669.  
  670.            Case Applets.System
  671.                Process.Start(ControlProcess, "/name Microsoft.System")
  672.  
  673.            Case Applets.SystemProperties
  674.                Process.Start(ControlProcess, "sysdm.cpl")
  675.  
  676.            Case Applets.TabletPCSettings
  677.                Process.Start(ControlProcess, "/name Microsoft.TabletPCSettings")
  678.  
  679.            Case Applets.TaskScheduler
  680.                Process.Start(ControlProcess, "schedtasks")
  681.  
  682.            Case Applets.Taskbar
  683.                Process.Start(ControlProcess, "/name Microsoft.Taskbar")
  684.  
  685.            Case Applets.TaskbarAndStartMenu
  686.                Process.Start(ControlProcess, "/name Microsoft.TaskbarAndStartMenu")
  687.  
  688.            Case Applets.TextToSpeech
  689.                Process.Start(ControlProcess, "/name Microsoft.TextToSpeech")
  690.  
  691.            Case Applets.Troubleshooting
  692.                Process.Start(ControlProcess, "/name Microsoft.Troubleshooting")
  693.  
  694.            Case Applets.UserAccounts
  695.                Process.Start(ControlProcess, "/name Microsoft.UserAccounts")
  696.  
  697.            Case Applets.WelcomeCenter
  698.                Process.Start(ControlProcess, "/name Microsoft.WelcomeCenter")
  699.  
  700.            Case Applets.WindowsAnytimeUpgrade
  701.                Process.Start(ControlProcess, "/name Microsoft.WindowsAnytimeUpgrade")
  702.  
  703.            Case Applets.WindowsCardSpace
  704.                Process.Start(ControlProcess, "/name Microsoft.CardSpace")
  705.  
  706.            Case Applets.WindowsDefender
  707.                Process.Start(ControlProcess, "/name Microsoft.WindowsDefender")
  708.  
  709.            Case Applets.WindowsFirewall
  710.                Process.Start(ControlProcess, "/name Microsoft.WindowsFirewall")
  711.  
  712.            Case Applets.WindowsMarketplace
  713.                Process.Start(ControlProcess, "/name Microsoft.GetProgramsOnline")
  714.  
  715.            Case Applets.WindowsMobilityCenter
  716.                Process.Start(ControlProcess, "/name Microsoft.MobilityCenter")
  717.  
  718.            Case Applets.WindowsSidebarProperties
  719.                Process.Start(ControlProcess, "/name Microsoft.WindowsSidebarProperties")
  720.  
  721.            Case Applets.WindowsSideShow
  722.                Process.Start(ControlProcess, "/name Microsoft.WindowsSideShow")
  723.  
  724.            Case Applets.WindowsUpdate
  725.                Process.Start(ControlProcess, "/name Microsoft.WindowsUpdate")
  726.  
  727.        End Select
  728.  
  729.    End Sub
  730.  
  731. #End Region
  732.  
  733. End Class
  734.  
  735.  
« Última modificación: 28 Septiembre 2014, 06:20 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #434 en: 2 Octubre 2014, 03:34 am »

He tomado una antigua class del cajón de los recuerdos (o experimentos xD) que servía como medidor de tiempo para un cronómetro o una cuenta atrás y lo he mejorado y simplificado bastante.

Ejemplo de uso:

Código
  1. Public Class form1
  2.  
  3.    ''' <summary>
  4.    ''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
  5.    ''' </summary>
  6.    Private WithEvents Clock As New TimeMeasurer With {.UpdateInterval = 100}
  7.  
  8.    Private ctrl_ElapsedTime As Control ' Control used to display the time elapsed interval.
  9.    Private ctrl_RemainingTime As Control ' Control used to display the time remaining interval.
  10.  
  11.    Private Shadows Sub Load() Handles MyBase.Load
  12.  
  13.        ctrl_ElapsedTime = Label1
  14.        ctrl_RemainingTime = Label2
  15.  
  16.        Me.Clock.Start(60000) ' Measure 1 minute
  17.  
  18.        ' Or...
  19.        ' Me.Clock.Stop() ' Stop temporally the time interval measurement.
  20.        ' Me.Clock.Resume() ' Resume a previouslly stopped time interval measurement.
  21.        ' Dim ClockState As TimeMeasurer.TimeMeasurerState = Me.Clock.State ' Get the state.
  22.  
  23.    End Sub
  24.  
  25.    Private Sub Clock_ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  26.    Handles Clock.ElapsedTimeUpdated
  27.  
  28.        ' Measure H:M:S:MS
  29.        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  30.                                              e.Hour, e.Minute, e.Second, e.Millisecond)
  31.  
  32.    End Sub
  33.  
  34.    Private Sub Clock_RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  35.    Handles Clock.RemainingTimeUpdated
  36.  
  37.        ' Measure H:M:S:MS
  38.        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  39.                                                e.Hour, e.Minute, e.Second, e.Millisecond)
  40.  
  41.        '' Measure H:M:S
  42.        'ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  43.        '                                        e.Hour, e.Minute, e.Second + 1)
  44.  
  45.    End Sub
  46.  
  47.    Private Sub Clock_ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  48.    Handles Clock.ElapsedTimeFinished
  49.  
  50.        ' Measure H:M:S:MS
  51.        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  52.                                              e.Hour, e.Minute, e.Second, e.Millisecond)
  53.  
  54.    End Sub
  55.  
  56.    Private Sub Clock_RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  57.    Handles Clock.RemainingTimeFinished
  58.  
  59.        ' Measure H:M:S:MS
  60.        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  61.                                                e.Hour, e.Minute, e.Second, e.Millisecond)
  62.  
  63.    End Sub
  64.  
  65. End Class

Como veis es muy sencillo de usar y de una manera más genérica (mucho más que el antiguo código que ecribí)

El source:

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 10-02-2014
  4. ' ***********************************************************************
  5. ' <copyright file="TimeMeasurer.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Public Class TimeMeasurer_Test
  13. '
  14. '    ''' <summary>
  15. '    ''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
  16. '    ''' </summary>
  17. '    Private WithEvents Clock As New TimeMeasurer With {.UpdateInterval = 100}
  18. '
  19. '    Private ctrl_ElapsedTime As Control ' Control used to display the time elapsed interval.
  20. '    Private ctrl_RemainingTime As Control ' Control used to display the time remaining interval.
  21. '
  22. '    Private Shadows Sub Load() Handles MyBase.Load
  23. '
  24. '        ctrl_ElapsedTime = LabelElapsed
  25. '        ctrl_RemainingTime = LabelRemaining
  26. '
  27. '        Me.Clock.Start(60000) ' Measure 1 minute
  28. '
  29. '        ' Or...
  30. '        ' Me.Clock.Stop() ' Stop temporally the time interval measurement.
  31. '        ' Me.Clock.Resume() ' Resume a previouslly stopped time interval measurement.
  32. '        ' Dim ClockState As TimeMeasurer.TimeMeasurerState = Me.Clock.State ' Get the state.
  33. '
  34. '    End Sub
  35. '
  36. '    ''' <summary>
  37. '    ''' Handles the ElapsedTimeUpdated event of the Clock instance.
  38. '    ''' </summary>
  39. '    ''' <param name="sender">The source of the event.</param>
  40. '    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
  41. '    Private Sub Clock_ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  42. '    Handles Clock.ElapsedTimeUpdated
  43. '
  44. '        ' Measure H:M:S:MS
  45. '        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  46. '                                              e.Hour, e.Minute, e.Second, e.Millisecond)
  47. '
  48. '        ' Measure H:M:S
  49. '        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  50. '                                              e.Hour, e.Minute, e.Second)
  51. '
  52. '    End Sub
  53. '
  54. '    ''' <summary>
  55. '    ''' Handles the RemainingTimeUpdated event of the Clock instance.
  56. '    ''' </summary>
  57. '    ''' <param name="sender">The source of the event.</param>
  58. '    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
  59. '    Private Sub Clock_RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  60. '    Handles Clock.RemainingTimeUpdated
  61. '
  62. '        ' Measure H:M:S:MS
  63. '        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  64. '                                                e.Hour, e.Minute, e.Second, e.Millisecond)
  65. '
  66. '        ' Measure H:M:S
  67. '        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  68. '                                                e.Hour, e.Minute, e.Second + 1)
  69. '
  70. '    End Sub
  71. '
  72. '    ''' <summary>
  73. '    ''' Handles the ElapsedTimeFinished event of the Clock instance.
  74. '    ''' </summary>
  75. '    ''' <param name="sender">The source of the event.</param>
  76. '    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
  77. '    Private Sub Clock_ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  78. '    Handles Clock.ElapsedTimeFinished
  79. '
  80. '        ' Measure H:M:S:MS
  81. '        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  82. '                                              e.Hour, e.Minute, e.Second, e.Millisecond)
  83. '
  84. '        ' Measure H:M:S
  85. '        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  86. '                                              e.Hour, e.Minute, e.Second)
  87. '
  88. '    End Sub
  89. '
  90. '    ''' <summary>
  91. '    ''' Handles the RemainingTimeFinished event of the Clock instance.
  92. '    ''' </summary>
  93. '    ''' <param name="sender">The source of the event.</param>
  94. '    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
  95. '    Private Sub Clock_RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
  96. '    Handles Clock.RemainingTimeFinished
  97. '
  98. '        ' Measure H:M:S:MS
  99. '        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
  100. '                                                e.Hour, e.Minute, e.Second, e.Millisecond)
  101. '
  102. '        ' Measure H:M:S
  103. '        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
  104. '                                                e.Hour, e.Minute, e.Second)
  105. '
  106. '    End Sub
  107. '
  108. 'End Class
  109.  
  110. #End Region
  111.  
  112. #Region " Option Statements "
  113.  
  114. Option Strict On
  115. Option Explicit On
  116. Option Infer Off
  117.  
  118. #End Region
  119.  
  120. #Region " Imports "
  121.  
  122. Imports System.ComponentModel
  123.  
  124. #End Region
  125.  
  126. ''' <summary>
  127. ''' Measure a time interval.
  128. ''' This can be used as a chronometer or countdown timer.
  129. ''' </summary>
  130. Public NotInheritable Class TimeMeasurer
  131.  
  132. #Region " Objects "
  133.  
  134.    ''' <summary>
  135.    ''' <see cref="Stopwatch"/> instance to retrieve the elapsed time.
  136.    ''' </summary>
  137.    Private TimeElapsed As Stopwatch
  138.  
  139.    ''' <summary>
  140.    ''' <see cref="TimeSpan"/> instance to retrieve the remaining time.
  141.    ''' </summary>
  142.    Private TimeRemaining As TimeSpan
  143.  
  144.    ''' <summary>
  145.    ''' <see cref="Timer"/> instance that updates the elapsed and remaining times and raises the events.
  146.    ''' </summary>
  147.    Private WithEvents MeasureTimer As Timer
  148.  
  149.    ''' <summary>
  150.    ''' Indicates wheter the <see cref="TimeMeasurer"/> instance has finished to measure intervals.
  151.    ''' </summary>
  152.    Private IsFinished As Boolean
  153.  
  154. #End Region
  155.  
  156. #Region " Properties "
  157.  
  158.    ''' <summary>
  159.    ''' Gets the current state of this <see cref="TimeMeasurer"/> instance.
  160.    ''' </summary>
  161.    ''' <value>The update interval.</value>
  162.    Public ReadOnly Property State As TimeMeasurerState
  163.        Get
  164.            If Me.IsFinished Then
  165.                Return TimeMeasurerState.Finished
  166.  
  167.            ElseIf (Me.TimeElapsed Is Nothing) OrElse Not (Me.TimeElapsed.IsRunning) Then
  168.                Return TimeMeasurerState.Stopped
  169.  
  170.            Else
  171.                Return TimeMeasurerState.Running
  172.  
  173.            End If
  174.        End Get
  175.    End Property
  176.  
  177.    ''' <summary>
  178.    ''' Gets or sets the update interval.
  179.    ''' </summary>
  180.    ''' <value>The update interval.</value>
  181.    Public Property UpdateInterval As Integer
  182.        Get
  183.            Return Me._UpdateInterval
  184.        End Get
  185.        Set(ByVal value As Integer)
  186.            Me._UpdateInterval = value
  187.            If Me.MeasureTimer IsNot Nothing Then
  188.                Me.MeasureTimer.Interval = value
  189.            End If
  190.        End Set
  191.    End Property
  192.    ''' <summary>
  193.    ''' The update interval
  194.    ''' </summary>
  195.    Private _UpdateInterval As Integer = 100I
  196.  
  197. #End Region
  198.  
  199. #Region " Enumerations "
  200.  
  201.    ''' <summary>
  202.    ''' Specifies the current state of a <see cref="TimeMeasurer"/> instance.
  203.    ''' </summary>
  204.    <Description("Enum used as return value of 'State' property.")>
  205.    Public Enum TimeMeasurerState As Integer
  206.  
  207.        ''' <summary>
  208.        ''' The <see cref="TimeMeasurer"/> instance is running and measuring time intervals.
  209.        ''' </summary>
  210.        Running = 0I
  211.  
  212.        ''' <summary>
  213.        ''' The <see cref="TimeMeasurer"/> instance is temporally stopped, waiting to resume.
  214.        ''' </summary>
  215.        Stopped = 1I
  216.  
  217.        ''' <summary>
  218.        ''' The <see cref="TimeMeasurer"/> instance has finished to measure the time intervals.
  219.        ''' </summary>
  220.        Finished = 2I
  221.  
  222.    End Enum
  223.  
  224. #End Region
  225.  
  226. #Region " Events "
  227.  
  228.    ''' <summary>
  229.    ''' Occurs when the elapsed time updates.
  230.    ''' </summary>
  231.    Public Event ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)
  232.  
  233.    ''' <summary>
  234.    ''' Occurs when the remaining time updates.
  235.    ''' </summary>
  236.    Public Event RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)
  237.  
  238.    ''' <summary>
  239.    ''' Occurs when the elapsed time finishes.
  240.    ''' </summary>
  241.    Public Event ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)
  242.  
  243.    ''' <summary>
  244.    ''' Occurs when the elapsed time finishes.
  245.    ''' </summary>
  246.    Public Event RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)
  247.  
  248.    ''' <summary>
  249.    ''' Contains the <see cref="TimeMeasureEventArgs"/> arguments.
  250.    ''' </summary>
  251.    Public Class TimeMeasureEventArgs : Inherits EventArgs
  252.  
  253.        ''' <summary>
  254.        ''' Gets or sets the hour.
  255.        ''' </summary>
  256.        ''' <value>The hour.</value>
  257.        Public Property Hour As Double
  258.  
  259.        ''' <summary>
  260.        ''' Gets or sets the minute.
  261.        ''' </summary>
  262.        ''' <value>The minute.</value>
  263.        Public Property Minute As Double
  264.  
  265.        ''' <summary>
  266.        ''' Gets or sets the Second.
  267.        ''' </summary>
  268.        ''' <value>The Second.</value>
  269.        Public Property Second As Double
  270.  
  271.        ''' <summary>
  272.        ''' Gets or sets the Millisecond.
  273.        ''' </summary>
  274.        ''' <value>The Millisecond.</value>
  275.        Public Property Millisecond As Double
  276.  
  277.    End Class
  278.  
  279. #End Region
  280.  
  281. #Region " Public Methods "
  282.  
  283.    ''' <summary>
  284.    ''' Starts the time interval measurement from zero.
  285.    ''' </summary>
  286.    ''' <param name="Milliseconds">Indicates the time interval to measure, in milliseconds.</param>
  287.    Public Sub Start(ByVal Milliseconds As Double)
  288.  
  289.        If Milliseconds > (TimeSpan.MaxValue.TotalMilliseconds - 1001.0R) Then
  290.            Throw New ArgumentOutOfRangeException("Milliseconds",
  291.                                                  String.Format("The value can't be greater than {0}",
  292.                                                                CStr(TimeSpan.MaxValue.TotalMilliseconds - 1001.0R)))
  293.        End If
  294.  
  295.        Me.TimeElapsed = New Stopwatch
  296.        Me.TimeRemaining = TimeSpan.FromMilliseconds(Milliseconds)
  297.        Me.MeasureTimer = New Timer With
  298.           {
  299.             .Tag = Milliseconds,
  300.             .Interval = Me.UpdateInterval,
  301.             .Enabled = True
  302.           }
  303.  
  304.        Me.TimeElapsed.Start()
  305.        Me.MeasureTimer.Start()
  306.  
  307.    End Sub
  308.  
  309.    ''' <summary>
  310.    ''' Stops the time interval measurement.
  311.    ''' </summary>
  312.    Public Sub [Stop]()
  313.  
  314.        If (Me.MeasureTimer Is Nothing) OrElse Not (Me.TimeElapsed.IsRunning) Then
  315.            Throw New Exception("TimeMeasurer is not running.")
  316.  
  317.        Else
  318.            Me.MeasureTimer.Stop()
  319.            Me.TimeElapsed.Stop()
  320.  
  321.        End If
  322.  
  323.    End Sub
  324.  
  325.    ''' <summary>
  326.    ''' Resumes the time interval measurement.
  327.    ''' </summary>
  328.    Public Sub [Resume]()
  329.  
  330.        If (Me.MeasureTimer Is Nothing) OrElse (Me.TimeElapsed.IsRunning) Then
  331.            Throw New Exception("TimeMeasurer is not stopped.")
  332.  
  333.        Else
  334.            Me.MeasureTimer.Start()
  335.            Me.TimeElapsed.Start()
  336.  
  337.        End If
  338.  
  339.    End Sub
  340.  
  341. #End Region
  342.  
  343. #Region " Private Methods "
  344.  
  345.    ''' <summary>
  346.    ''' Stops Time intervals and resets the elapsed and remaining time to zero.
  347.    ''' </summary>
  348.    Private Sub Reset()
  349.  
  350.        Me.MeasureTimer.Stop()
  351.        Me.TimeElapsed.Reset()
  352.  
  353.    End Sub
  354.  
  355. #End Region
  356.  
  357. #Region " Event Handlers "
  358.  
  359.    ''' <summary>
  360.    ''' Handles the Tick event of the MeasureTimer control.
  361.    ''' </summary>
  362.    ''' <param name="sender">The source of the event.</param>
  363.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  364.    Private Sub MeasureTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
  365.    Handles MeasureTimer.Tick
  366.  
  367.        Dim TimeDifference As TimeSpan = (Me.TimeRemaining - Me.TimeElapsed.Elapsed)
  368.        Dim ElapsedArgs As New TimeMeasureEventArgs
  369.        Dim RemainingArgs As New TimeMeasureEventArgs
  370.  
  371.        If (TimeDifference.TotalMilliseconds <= 0.0R) _
  372.        OrElse (Me.TimeElapsed.ElapsedMilliseconds > DirectCast(Me.MeasureTimer.Tag, Double)) Then
  373.  
  374.            Dim TotalTime As TimeSpan = TimeSpan.FromMilliseconds(DirectCast(Me.MeasureTimer.Tag, Double))
  375.  
  376.            With ElapsedArgs
  377.                .Hour = TotalTime.Hours
  378.                .Minute = TotalTime.Minutes
  379.                .Second = TotalTime.Seconds
  380.                .Millisecond = TotalTime.Milliseconds
  381.            End With
  382.  
  383.            With RemainingArgs
  384.                .Hour = 0.0R
  385.                .Minute = 0.0R
  386.                .Second = 0.0R
  387.                .Millisecond = 0.0R
  388.            End With
  389.  
  390.            Me.Reset()
  391.            Me.IsFinished = True
  392.            RaiseEvent ElapsedTimeFinished(Me.TimeElapsed, ElapsedArgs)
  393.            RaiseEvent RemainingTimeFinished(TimeDifference, RemainingArgs)
  394.  
  395.        Else
  396.  
  397.            With ElapsedArgs
  398.                .Hour = TimeElapsed.Elapsed.Hours
  399.                .Minute = TimeElapsed.Elapsed.Minutes
  400.                .Second = TimeElapsed.Elapsed.Seconds
  401.                .Millisecond = TimeElapsed.Elapsed.Milliseconds
  402.            End With
  403.  
  404.            With RemainingArgs
  405.                .Hour = Math.Floor(TimeDifference.TotalHours) Mod TimeSpan.MaxValue.TotalMilliseconds
  406.                .Minute = Math.Floor(TimeDifference.TotalMinutes) Mod 60.0R
  407.                .Second = Math.Floor(TimeDifference.TotalSeconds) Mod 60.0R
  408.                .Millisecond = Math.Floor(TimeDifference.TotalMilliseconds Mod 1000.0R)
  409.            End With
  410.  
  411.            RaiseEvent ElapsedTimeUpdated(Me.TimeElapsed, ElapsedArgs)
  412.            RaiseEvent RemainingTimeUpdated(TimeDifference, RemainingArgs)
  413.  
  414.        End If
  415.  
  416.    End Sub
  417.  
  418. #End Region
  419.  
  420. End Class
« Última modificación: 2 Octubre 2014, 03:44 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #435 en: 2 Octubre 2014, 04:12 am »

Bueno, ya que nadie me da nunca las gracias por mis aportaciones de Snippets los cuales voy publicando casi día tras día o semana tras semana, y ya que no recibo ni un piropo ni una sonrisa por esto (xD), pues escribo este OffTopic para darme un poquito de reconocimiento a mi mismo, porque yo lo valgo xD.

Así es un día cualquiera en la vida de Elektro actualizando un antiguo Snippet (los breakpoints creo que no se restauran al darle ctrl+z), esto es para que veais que le pongo mucho empeño para compartir códigos con todos vosotros... y que todo es de cosecha propia, bueno, y porque en realidad siempre quise hacer algún video de este estilo a lo speed-coding, aunque no he elegido el mejor código/snippet para hacer este tipo de video, pero tenia muchas ganas de hacerlo xD:



Si, ha sido una chorrada de video y de comentario, ¿y que?, ¡a ver si os animais a compartir Snippets!... que siempre soy el único :(

Saludos!
« Última modificación: 2 Octubre 2014, 06:43 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #436 en: 2 Octubre 2014, 06:31 am »

Ejemplo de como crear una propiedad con un rango asignado...

Código
  1. Public Class MyType
  2.  
  3. ''' <summary>
  4. ''' Gets or sets the value.
  5. ''' </summary>
  6. ''' <value>The value.</value>
  7. Public Property MyProperty As Integer
  8.    Get
  9.        Return Me._MyValue
  10.    End Get
  11.    Set(ByVal value As Integer)
  12.  
  13.        If value < Me._MyValueMin Then
  14.            If Me._MyValueThrowRangeException Then
  15.                Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage)
  16.            End If
  17.            Me._MyValue = Me._MyValueMin
  18.  
  19.        ElseIf value > Me._MyValueMax Then
  20.            If Me._MyValueThrowRangeException Then
  21.                Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage)
  22.            End If
  23.            Me._MyValue = Me._MyValueMax
  24.  
  25.        Else
  26.            Me._MyValue = value
  27.  
  28.        End If
  29.  
  30.    End Set
  31. End Property
  32. Private _MyValue As Integer = 0I
  33. Private _MyValueMin As Integer = 0I
  34. Private _MyValueMax As Integer = 10I
  35. Private _MyValueThrowRangeException As Boolean = True
  36.    Private _MyValueExceptionMessage As String = String.Format("The valid range is beetwen {0} and {1}",
  37.                                                           Me._MyValueMin, Me._MyValueMax)
  38.  
  39. End Class




Una utilidad para mostrar, ocultar, o intercambiar el estado del escritorio.

Nota: El método ToggleDesktop no funciona en WinXP.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 09-23-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DesktopVisibility.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ' DesktopVisibility.ShowDesktop()
  13. ' DesktopVisibility.HideDesktop()
  14. ' DesktopVisibility.ToggleDesktop()
  15.  
  16. #End Region
  17.  
  18. #Region " Imports "
  19.  
  20. Imports System.Runtime.InteropServices
  21.  
  22. #End Region
  23.  
  24. #Region " DesktopVisibility "
  25.  
  26. ''' <summary>
  27. ''' Shows, hides, or toggles the desktop.
  28. ''' </summary>
  29. Public NotInheritable Class DesktopVisibility
  30.  
  31. #Region " Objects "
  32.  
  33.    ''' <summary>
  34.    ''' "Shell" CLASSID.
  35.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776890%28v=vs.85%29.aspx
  36.    ''' </summary>
  37.    Private Shared ReadOnly CLSIDShell As New Guid("13709620-C279-11CE-A49E-444553540000")
  38.  
  39.    ''' <summary>
  40.    ''' Gets the objects in the Shell.
  41.    ''' Methods are provided to control the Shell and to execute commands within the Shell.
  42.    ''' There are also methods to obtain other Shell-related objects.
  43.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb774094%28v=vs.85%29.aspx
  44.    ''' </summary>
  45.    Private Shared ReadOnly Property Shell As Object
  46.        Get
  47.            If _Shell Is Nothing Then
  48.                _Shell = Activator.CreateInstance(Type.GetTypeFromCLSID(CLSIDShell))
  49.                Return _Shell
  50.            Else
  51.                Return _Shell
  52.            End If
  53.        End Get
  54.    End Property
  55.    Private Shared _Shell As Object = Nothing
  56.  
  57. #End Region
  58.  
  59. #Region " P/Invoke "
  60.  
  61. #Region " Methods "
  62.  
  63.    ''' <summary>
  64.    ''' Retrieves a handle to the top-level window whose class name and window name match the specified strings.
  65.    ''' This function does not search child windows.
  66.    ''' This function does not perform a case-sensitive search.
  67.    ''' To search child windows, beginning with a specified child window, use the FindWindowEx function.
  68.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499%28v=vs.85%29.aspx
  69.    ''' </summary>
  70.    ''' <param name="lpClassName">The class name.
  71.    ''' If this parameter is NULL, it finds any window whose title matches the lpWindowName parameter.</param>
  72.    ''' <param name="lpWindowName">The window name (the window's title).
  73.    ''' If this parameter is NULL, all window names match.</param>
  74.    ''' <returns>If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
  75.    ''' If the function fails, the return value is NULL.</returns>
  76.    <DllImport("user32.dll", SetLastError:=False)>
  77.    Private Shared Function FindWindow(
  78.            ByVal lpClassName As String,
  79.            ByVal lpWindowName As String
  80.    ) As IntPtr
  81.    End Function
  82.  
  83.    ''' <summary>
  84.    ''' Sends the specified message to a window or windows.
  85.    ''' The SendMessage function calls the window procedure for the specified window
  86.    ''' and does not return until the window procedure has processed the message.
  87.    ''' </summary>
  88.    ''' <param name="hWnd">A handle to the window whose window procedure will receive the message.</param>
  89.    ''' <param name="Msg">The message to be sent.</param>
  90.    ''' <param name="wParam">Additional message-specific information.</param>
  91.    ''' <param name="lParam">Additional message-specific information.</param>
  92.    ''' <returns>IntPtr.</returns>
  93.    <DllImport("user32.dll", SetLastError:=False)>
  94.    Private Shared Function SendMessage(
  95.            ByVal hWnd As IntPtr,
  96.            ByVal Msg As WindowsMessages,
  97.            ByVal wParam As IntPtr,
  98.            ByVal lParam As IntPtr
  99.    ) As IntPtr
  100.    End Function
  101.  
  102. #End Region
  103.  
  104. #Region " Enumerations "
  105.  
  106.    ''' <summary>
  107.    ''' Specifies a System-Defined Message.
  108.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644927%28v=vs.85%29.aspx#system_defined
  109.    ''' </summary>
  110.    Public Enum WindowsMessages
  111.  
  112.        ''' <summary>
  113.        ''' Message sent when the user selects a command item from a menu,
  114.        ''' when a control sends a notification message to its parent window,
  115.        ''' or when an accelerator keystroke is translated.
  116.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms647591%28v=vs.85%29.aspx
  117.        ''' </summary>
  118.        WM_COMMAND = &H111UI
  119.  
  120.    End Enum
  121.  
  122. #End Region
  123.  
  124. #Region " Constants "
  125.  
  126.    ''' <summary>
  127.    ''' Minimize all windows.
  128.    ''' </summary>
  129.    Const MIN_ALL As Integer = 419
  130.  
  131.    ''' <summary>
  132.    ''' Undo the minimization of all minimized windows.
  133.    ''' </summary>
  134.    Const MIN_ALL_UNDO As Integer = 416
  135.  
  136. #End Region
  137.  
  138. #End Region
  139.  
  140. #Region " Public Methods "
  141.  
  142.    ''' <summary>
  143.    ''' Shows the desktop.
  144.    ''' </summary>
  145.    Public Shared Sub ShowDesktop()
  146.  
  147.        SendMessage(FindWindow("Shell_TrayWnd", Nothing),
  148.                    WindowsMessages.WM_COMMAND,
  149.                    New IntPtr(MIN_ALL), IntPtr.Zero)
  150.  
  151.    End Sub
  152.  
  153.    ''' <summary>
  154.    ''' Hides the desktop.
  155.    ''' </summary>
  156.    Public Shared Sub HideDesktop()
  157.  
  158.        SendMessage(FindWindow("Shell_TrayWnd", Nothing),
  159.                    WindowsMessages.WM_COMMAND,
  160.                    New IntPtr(MIN_ALL_UNDO), IntPtr.Zero)
  161.  
  162.    End Sub
  163.  
  164.    ''' <summary>
  165.    ''' Shows or hides the desktop.
  166.    ''' </summary>
  167.    Public Shared Sub ToggleDesktop()
  168.  
  169.        Shell.ToggleDesktop() ' Doesns't works in Windows XP
  170.  
  171.    End Sub
  172.  
  173. #End Region
  174.  
  175. End Class
  176.  
  177. #End Region





Utilidad para posicionar una ventana en la pantalla, se puede elegir una de las posiciones predeterminadas (las esquinas de la pantalla) o especificar unas coordenadas exactas.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 10-01-2014
  4. ' ***********************************************************************
  5. ' <copyright file="SetWindowPosition.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Example Usage "
  11.  
  12. ' SetWindowPosition.SetWindowPos("proceso.exe", SetWindowPosition.Corner.BottomRight)
  13. ' SetWindowPosition.SetWindowPos("proceso.exe", X:=100, Y:=100, Bounds:=SystemInformation.VirtualScreen)
  14.  
  15. #End Region
  16.  
  17. #Region " Imports "
  18.  
  19. Imports System.ComponentModel
  20. Imports System.Runtime.InteropServices
  21.  
  22. #End Region
  23.  
  24. ''' <summary>
  25. ''' Set the position of a window.
  26. ''' </summary>
  27. Public Class SetWindowPosition
  28.  
  29. #Region " P/Invoke "
  30.  
  31.    ''' <summary>
  32.    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
  33.    ''' This class does not suppress stack walks for unmanaged code permission.
  34.    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
  35.    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
  36.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
  37.    ''' </summary>
  38.    Protected NotInheritable Class NativeMethods
  39.  
  40. #Region " Methods "
  41.  
  42.        ''' <summary>
  43.        ''' Changes the size, position, and Z order of a child, pop-up, or top-level window.
  44.        ''' These windows are ordered according to their appearance on the screen.
  45.        ''' The topmost window receives the highest rank and is the first window in the Z order.
  46.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
  47.        ''' </summary>
  48.        ''' <param name="hWnd">
  49.        ''' A handle to the window.
  50.        ''' </param>
  51.        ''' <param name="hWndInsertAfter">
  52.        ''' A special handle to the window to precede the positioned window in the Z order.
  53.        ''' This parameter must be a window handle or one of the <see cref="SpecialWindowHandles"/> values.
  54.        ''' </param>
  55.        ''' <param name="X">
  56.        ''' The new position of the left side of the window, in client coordinates.
  57.        ''' </param>
  58.        ''' <param name="Y">
  59.        ''' The new position of the top of the window, in client coordinates.
  60.        ''' </param>
  61.        ''' <param name="cx">
  62.        ''' The new width of the window, in pixels.
  63.        ''' </param>
  64.        ''' <param name="cy">
  65.        ''' The new height of the window, in pixels.
  66.        ''' </param>
  67.        ''' <param name="uFlags">
  68.        ''' The window sizing and positioning flags.
  69.        ''' </param>
  70.        ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  71.        <DllImport("user32.dll", SetLastError:=True)>
  72.        Friend Shared Function SetWindowPos(
  73.               ByVal hWnd As IntPtr,
  74.               ByVal hWndInsertAfter As SpecialWindowHandles,
  75.               ByVal X As Integer,
  76.               ByVal Y As Integer,
  77.               ByVal cx As Integer,
  78.               ByVal cy As Integer,
  79.               ByVal uFlags As SetWindowPosFlags
  80.        ) As Boolean
  81.        End Function
  82.  
  83.        ''' <summary>
  84.        ''' Retrieves the dimensions of the bounding rectangle of the specified window.
  85.        ''' The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
  86.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633519%28v=vs.85%29.aspx
  87.        ''' </summary>
  88.        ''' <param name="hWnd">A handle to the window.</param>
  89.        ''' <param name="rc">
  90.        ''' A pointer to a RECT structure that receives the screen coordinates of
  91.        ''' the upper-left and lower-right corners of the window.
  92.        ''' </param>
  93.        ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  94.        <DllImport("user32.dll", SetLastError:=True)>
  95.        Friend Shared Function GetWindowRect(
  96.               ByVal hWnd As IntPtr,
  97.               ByRef rc As Rectangle
  98.        ) As Boolean
  99.        End Function
  100.  
  101. #End Region
  102.  
  103. #Region " Enumerations "
  104.  
  105.        ''' <summary>
  106.        ''' Specifies the window sizing and positioning flags.
  107.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
  108.        ''' </summary>
  109.        <Description("Enum used as 'uFlags' parameter of 'NativeMethods.SetWindowPos' function")>
  110.        <Flags>
  111.        Friend Enum SetWindowPosFlags As UInteger
  112.  
  113.            ''' <summary>
  114.            ''' If the calling thread and the thread that owns the window are attached to different input queues,
  115.            ''' the system posts the request to the thread that owns the window.
  116.            ''' This prevents the calling thread from blocking its execution while other threads process the request.
  117.            ''' </summary>
  118.            ''' <remarks>SWP_ASYNCWINDOWPOS</remarks>
  119.            SynchronousWindowPosition = &H4000UI
  120.  
  121.            ''' <summary>
  122.            ''' Prevents generation of the WM_SYNCPAINT message.
  123.            ''' </summary>
  124.            ''' <remarks>SWP_DEFERERASE</remarks>
  125.            DeferErase = &H2000UI
  126.  
  127.            ''' <summary>
  128.            ''' Draws a frame (defined in the window's class description) around the window.
  129.            ''' </summary>
  130.            ''' <remarks>SWP_DRAWFRAME</remarks>
  131.            DrawFrame = &H20UI
  132.  
  133.            ''' <summary>
  134.            ''' Applies new frame styles set using the SetWindowLong function.
  135.            ''' Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed.
  136.            ''' If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
  137.            ''' </summary>
  138.            ''' <remarks>SWP_FRAMECHANGED</remarks>
  139.            FrameChanged = &H20UI
  140.  
  141.            ''' <summary>
  142.            ''' Hides the window.
  143.            ''' </summary>
  144.            ''' <remarks>SWP_HIDEWINDOW</remarks>
  145.            HideWindow = &H80UI
  146.  
  147.            ''' <summary>
  148.            ''' Does not activate the window.
  149.            ''' If this flag is not set, the window is activated and moved to the top of
  150.            ''' either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
  151.            ''' </summary>
  152.            ''' <remarks>SWP_NOACTIVATE</remarks>
  153.            DoNotActivate = &H10UI
  154.  
  155.            ''' <summary>
  156.            ''' Discards the entire contents of the client area. If this flag is not specified,
  157.            ''' the valid contents of the client area are saved and copied back into the
  158.            ''' client area after the window is sized or repositioned.
  159.            ''' </summary>
  160.            ''' <remarks>SWP_NOCOPYBITS</remarks>
  161.            DoNotCopyBits = &H100UI
  162.  
  163.            ''' <summary>
  164.            ''' Retains the current position (ignores X and Y parameters).
  165.            ''' </summary>
  166.            ''' <remarks>SWP_NOMOVE</remarks>
  167.            IgnoreMove = &H2UI
  168.  
  169.            ''' <summary>
  170.            ''' Does not change the owner window's position in the Z order.
  171.            ''' </summary>
  172.            ''' <remarks>SWP_NOOWNERZORDER</remarks>
  173.            DoNotChangeOwnerZOrder = &H200UI
  174.  
  175.            ''' <summary>
  176.            ''' Does not redraw changes.
  177.            ''' If this flag is set, no repainting of any kind occurs.
  178.            ''' This applies to  the client area, the nonclient area (including the title bar and scroll bars),
  179.            ''' and any part of the parent window uncovered as a result of the window being moved.
  180.            ''' When this flag is set, the application must explicitly invalidate or
  181.            ''' redraw any parts of the window and parent window that need redrawing.
  182.            ''' </summary>
  183.            ''' <remarks>SWP_NOREDRAW</remarks>
  184.            DoNotRedraw = &H8UI
  185.  
  186.            ''' <summary>
  187.            ''' Same as the SWP_NOOWNERZORDER flag.
  188.            ''' </summary>
  189.            ''' <remarks>SWP_NOREPOSITION</remarks>
  190.            DoNotReposition = &H200UI
  191.  
  192.            ''' <summary>
  193.            ''' Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
  194.            ''' </summary>
  195.            ''' <remarks>SWP_NOSENDCHANGING</remarks>
  196.            DoNotSendChangingEvent = &H400UI
  197.  
  198.            ''' <summary>
  199.            ''' Retains the current size (ignores the cx and cy parameters).
  200.            ''' </summary>
  201.            ''' <remarks>SWP_NOSIZE</remarks>
  202.            IgnoreResize = &H1UI
  203.  
  204.            ''' <summary>
  205.            ''' Retains the current Z order (ignores the hWndInsertAfter parameter).
  206.            ''' </summary>
  207.            ''' <remarks>SWP_NOZORDER</remarks>
  208.            IgnoreZOrder = &H4UI
  209.  
  210.            ''' <summary>
  211.            ''' Displays the window.
  212.            ''' </summary>
  213.            ''' <remarks>SWP_SHOWWINDOW</remarks>
  214.            ShowWindow = &H40UI
  215.  
  216.        End Enum
  217.  
  218.        ''' <summary>
  219.        ''' Specifies a special handle to the window to precede the positioned window in the Z order.
  220.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
  221.        ''' </summary>
  222.        <Description("Enum used as 'hWndInsertAfter' parameter of 'NativeMethods.SetWindowPos' function")>
  223.        Friend Enum SpecialWindowHandles As Integer
  224.  
  225.            ''' <summary>
  226.            ''' Places the window at the top of the Z order.
  227.            ''' </summary>
  228.            Top = 0I
  229.  
  230.            ''' <summary>
  231.            ''' Places the window at the bottom of the Z order.
  232.            ''' If the hWnd parameter identifies a topmost window,
  233.            ''' the window loses its topmost status and is placed at the bottom of all other windows.
  234.            ''' </summary>
  235.            Bottom = 1I
  236.  
  237.            ''' <summary>
  238.            ''' Places the window above all non-topmost windows.
  239.            ''' The window maintains its topmost position even when it is deactivated.
  240.            ''' </summary>
  241.            TopMost = -1I
  242.  
  243.            ''' <summary>
  244.            ''' Places the window above all non-topmost windows (that is, behind all topmost windows).
  245.            ''' This flag has no effect if the window is already a non-topmost window.
  246.            ''' </summary>
  247.            NoTopMost = -2I
  248.  
  249.        End Enum
  250.  
  251. #End Region
  252.  
  253.    End Class
  254.  
  255. #End Region
  256.  
  257. #Region " Enumerations "
  258.  
  259.    ''' <summary>
  260.    ''' Specifies a screen corner.
  261.    ''' </summary>
  262.    <Description("Enum used as 'Corner' parameter of 'SetWindowPos' function")>
  263.    Friend Enum Corner As Integer
  264.  
  265.        ''' <summary>
  266.        ''' Top-Left screen corner.
  267.        ''' </summary>
  268.        TopLeft = 0I
  269.  
  270.        ''' <summary>
  271.        ''' Top-Right screen corner.
  272.        ''' </summary>
  273.        TopRight = 1I
  274.  
  275.        ''' <summary>
  276.        ''' Bottom-Left screen corner.
  277.        ''' </summary>
  278.        BottomLeft = 2I
  279.        ''' <summary>
  280.        ''' Bottom-Right screen corner.
  281.        ''' </summary>0
  282.        BottomRight = 3I
  283.  
  284.    End Enum
  285.  
  286. #End Region
  287.  
  288. #Region " Public Methods "
  289.  
  290.    ''' <summary>
  291.    ''' Set the position of a window.
  292.    ''' </summary>
  293.    ''' <param name="ProcessName">The process name.</param>
  294.    ''' <param name="Corner">The new window position, a screen corner.</param>
  295.    ''' <param name="Bounds">
  296.    ''' The screen <see cref="Rectangle"/> where the window is shown.
  297.    ''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
  298.    ''' </param>
  299.    Friend Shared Sub SetWindowPos(ByVal ProcessName As String,
  300.                                   ByVal Corner As Corner,
  301.                                   Optional ByVal Bounds As Rectangle = Nothing)
  302.  
  303.        Dim Rect As Rectangle  ' The specified screen bounds
  304.        Dim HWND As IntPtr     ' The process main window handle.
  305.        Dim Width As Integer   ' The process window width.
  306.        Dim Height As Integer  ' The process window height.
  307.        Dim x As Integer
  308.        Dim y As Integer
  309.  
  310.        If Bounds.IsEmpty Then
  311.            Bounds = Screen.PrimaryScreen.WorkingArea
  312.        End If
  313.  
  314.        ' Iterate the process instances.
  315.        For Each p As Process In Process.GetProcessesByName(FixProcessName(ProcessName))
  316.  
  317.            Try
  318.                ' Get the main window handle.
  319.                HWND = p.MainWindowHandle
  320.  
  321.                ' Copy the process window position and size into the Rectangle.
  322.                ' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
  323.                NativeMethods.GetWindowRect(HWND, Rect)
  324.                Width = (Rect.Width - Rect.Left)    ' Set the window width
  325.                Height = (Rect.Height - Rect.Top) ' Set the window height
  326.  
  327.                Select Case Corner
  328.  
  329.                    Case SetWindowPosition.Corner.TopLeft
  330.                        x = Bounds.Left
  331.                        y = Bounds.Top
  332.  
  333.                    Case SetWindowPosition.Corner.TopRight
  334.                        x = Bounds.Right - Width
  335.                        y = Bounds.Top
  336.  
  337.                    Case SetWindowPosition.Corner.BottomLeft
  338.                        x = Bounds.Left
  339.                        y = Bounds.Bottom - Height
  340.  
  341.                    Case SetWindowPosition.Corner.BottomRight
  342.                        x = Bounds.Right - Width
  343.                        y = Bounds.Bottom - Height
  344.  
  345.                End Select
  346.  
  347.                ' Move the Main Window.
  348.                NativeMethods.SetWindowPos(HWND, New IntPtr(NativeMethods.SpecialWindowHandles.NoTopMost),
  349.                                           x, y, 0, 0,
  350.                                           NativeMethods.SetWindowPosFlags.IgnoreResize)
  351.  
  352.            Catch ex As Exception
  353.                Throw
  354.  
  355.            End Try
  356.  
  357.        Next
  358.  
  359.    End Sub
  360.  
  361.    ''' <summary>
  362.    ''' Set the position of a window.
  363.    ''' </summary>
  364.    ''' <param name="ProcessName">The process name.</param>
  365.    ''' <param name="X">The new X coordinate.</param>
  366.    ''' <param name="Y">The new Y coordinate.</param>
  367.    ''' <param name="Bounds">
  368.    ''' The screen <see cref="Rectangle"/> where the window is shown.
  369.    ''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
  370.    ''' </param>
  371.    Friend Shared Sub SetWindowPos(ByVal ProcessName As String,
  372.                             ByVal X As Integer,
  373.                             ByVal Y As Integer,
  374.                             Optional ByVal Bounds As Rectangle = Nothing)
  375.  
  376.        Dim Rect As Rectangle  ' The specified screen bounds
  377.        Dim HWND As IntPtr     ' The process main window handle.
  378.        Dim Width As Integer   ' The process window width.
  379.        Dim Height As Integer  ' The process window height.
  380.  
  381.        If Bounds.IsEmpty Then
  382.            Bounds = Screen.PrimaryScreen.WorkingArea
  383.        End If
  384.  
  385.        ' Iterate the process instances.
  386.        For Each p As Process In Process.GetProcessesByName(FixProcessName(ProcessName))
  387.  
  388.            Try
  389.                ' Get the main window handle.
  390.                HWND = p.MainWindowHandle
  391.  
  392.                ' Copy the process window position and size into the Rectangle.
  393.                ' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
  394.                NativeMethods.GetWindowRect(HWND, Rect)
  395.                Width = (Rect.Width - Rect.Left)  ' Set the window width
  396.                Height = (Rect.Height - Rect.Top) ' Set the window height
  397.  
  398.                ' Move the Main Window.
  399.                NativeMethods.SetWindowPos(HWND, New IntPtr(NativeMethods.SpecialWindowHandles.NoTopMost),
  400.                                           x, y, 0, 0,
  401.                                           NativeMethods.SetWindowPosFlags.IgnoreResize)
  402.  
  403.            Catch ex As Exception
  404.                Throw
  405.  
  406.            End Try
  407.  
  408.        Next
  409.  
  410.    End Sub
  411.  
  412. #End Region
  413.  
  414. #Region " Private Methods "
  415.  
  416.    ''' <summary>
  417.    ''' Fixes the name of a process.
  418.    ''' </summary>
  419.    ''' <param name="name">The process name.</param>
  420.    ''' <returns>System.String.</returns>
  421.    Private Shared Function FixProcessName(ByVal name As String) As String
  422.  
  423.        If name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
  424.            Return name.Remove(name.Length - ".exe".Length)
  425.        Else
  426.            Return name
  427.        End If
  428.  
  429.    End Function
  430.  
  431. #End Region
  432.  
  433. End Class
  434.  





Añade o elimina una aplicación de la sección 'Run' del registro, para iniciar una aplicación cuando el usuario se loguea en Windows.

Código
  1.        ' Add or remove application from Windows Startup
  2.        ' ( By Elektro )
  3.        '
  4.        ' Usage Examples :
  5.        ' AddApplicationToWindowsStartup(User.CurrentUser, Application.ProductName, Application.ExecutablePath)
  6.        ' RemoveApplicationFromWindowsStartup(User.CurrentUser, pplication.ProductName)
  7.  
  8.        ''' <summary>
  9.        ''' Specifies a registry user session.
  10.        ''' </summary>
  11.        Public Enum User As Integer
  12.  
  13.            ''' <summary>
  14.            ''' The current user session.
  15.            ''' </summary>
  16.            CurrentUser = 1I
  17.  
  18.            ''' <summary>
  19.            ''' All user sessions.
  20.            ''' </summary>
  21.            AllUsers = 2I
  22.  
  23.        End Enum
  24.  
  25.        ''' <summary>
  26.        ''' Adds an application to Windows Startup.
  27.        ''' </summary>
  28.        ''' <param name="User">Indicates the registry root key.</param>
  29.        ''' <param name="Title">Indicates the registry value name.</param>
  30.        ''' <param name="FilePath">Indicates the registry value data.</param>
  31.        Friend Shared Sub AddApplicationToWindowsStartup(ByVal User As User,
  32.                                                         ByVal Title As String,
  33.                                                         ByVal FilePath As String)
  34.  
  35.            Try
  36.                Select Case User
  37.  
  38.                    Case User.CurrentUser
  39.                        My.Computer.Registry.CurrentUser.
  40.                        OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
  41.                        SetValue(Title, FilePath, Microsoft.Win32.RegistryValueKind.String)
  42.  
  43.                    Case User.AllUsers
  44.                        My.Computer.Registry.LocalMachine.
  45.                        OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
  46.                        SetValue(Title, FilePath, Microsoft.Win32.RegistryValueKind.String)
  47.  
  48.                    Case Else
  49.                        Exit Select
  50.  
  51.                End Select
  52.  
  53.            Catch ex As Exception
  54.                Throw
  55.  
  56.            End Try
  57.  
  58.        End Sub
  59.  
  60.        ''' <summary>
  61.        ''' Removes an application from Windows Startup.
  62.        ''' </summary>
  63.        ''' <param name="User">Indicates the registry root key.</param>
  64.        ''' <param name="Title">Indicates the registry value name.</param>
  65.        Friend Shared Sub RemoveApplicationFromWindowsStartup(ByVal User As User,
  66.                                                              ByVal Title As String)
  67.            Try
  68.  
  69.                Select Case User
  70.  
  71.                    Case User.CurrentUser
  72.                        My.Computer.Registry.CurrentUser.
  73.                        OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
  74.                        DeleteValue(Title, throwOnMissingValue:=False)
  75.  
  76.                    Case User.AllUsers
  77.                        My.Computer.Registry.LocalMachine.
  78.                        OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
  79.                        DeleteValue(Title, throwOnMissingValue:=False)
  80.  
  81.                    Case Else
  82.                        Exit Select
  83.  
  84.                End Select
  85.  
  86.            Catch ex As Exception
  87.                Throw
  88.  
  89.            End Try
  90.  
  91.        End Sub





Obtiene la ruta de un proceso de 64 Bits, desde una aplicación .NET de 32 Bits.

Aviso, es un procedimiento lento, pero por el momento no conozco una mejor manera de lograrlo.

Código
  1.    ' Get x64 Process Path From x86
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.Management'
  6.    '
  7.    ' Usage Examples:
  8.    ' Dim path As String = GetX64ProcessPathFromX86("conhost.exe")
  9.    '
  10.    ''' <summary>
  11.    ''' Gets the process path of an x64 process from an x86 .NET application.
  12.    ''' </summary>
  13.    ''' <param name="ProcessName">Indicates the name of the process.</param>
  14.    ''' <returns>The process path.</returns>
  15.    Friend Shared Function GetX64ProcessPathFromX86(ByVal ProcessName As String) As String
  16.  
  17.        Dim wmiQuery As String = String.Format("SELECT ExecutablePath FROM Win32_Process Where Name = '{0}.exe'",
  18.                                               If(ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase),
  19.                                                  ProcessName.Remove(ProcessName.Length - ".exe".Length),
  20.                                                  ProcessName))
  21.  
  22.        Using searcher As New ManagementObjectSearcher(queryString:=wmiQuery)
  23.  
  24.            Using results As ManagementObjectCollection = searcher.[Get]
  25.  
  26.                If results.Count <> 0I Then
  27.  
  28.                    Return DirectCast(DirectCast(results(0I), ManagementBaseObject).
  29.                                      Properties("ExecutablePath").Value, String)
  30.  
  31.                Else
  32.                    Return String.Empty
  33.  
  34.                End If
  35.  
  36.            End Using
  37.  
  38.        End Using
  39.  
  40.    End Function

« Última modificación: 2 Octubre 2014, 06:42 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #437 en: 2 Octubre 2014, 06:39 am »

Modifica el estado de una ventana.

Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 10-02-2014
  4. ' ***********************************************************************
  5. ' <copyright file="SetWindowState.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Dim HWND As IntPtr = Process.GetProcessesByName("devenv").First.MainWindowHandle
  13. '
  14. 'SetWindowState.SetWindowState(HWND, SetWindowState.WindowState.Hide)
  15. 'SetWindowState.SetWindowState("devenv", SetWindowState.WindowState.Restore, Recursivity:=False)
  16.  
  17. #End Region
  18.  
  19. #Region " Imports "
  20.  
  21. Imports System.Runtime.InteropServices
  22.  
  23. #End Region
  24.  
  25. ''' <summary>
  26. ''' Sets the state of a window.
  27. ''' </summary>
  28. Public NotInheritable Class SetWindowState
  29.  
  30. #Region " P/Invoke "
  31.  
  32.    ''' <summary>
  33.    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
  34.    ''' This class does not suppress stack walks for unmanaged code permission.
  35.    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
  36.    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
  37.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
  38.    ''' </summary>
  39.    Protected NotInheritable Class NativeMethods
  40.  
  41. #Region " Methods "
  42.  
  43.        ''' <summary>
  44.        ''' Retrieves a handle to the top-level window whose class name and window name match the specified strings.
  45.        ''' This function does not search child windows.
  46.        ''' This function does not perform a case-sensitive search.
  47.        ''' To search child windows, beginning with a specified child window, use the FindWindowEx function.
  48.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499%28v=vs.85%29.aspx
  49.        ''' </summary>
  50.        ''' <param name="lpClassName">The class name.
  51.        ''' If this parameter is NULL, it finds any window whose title matches the lpWindowName parameter.</param>
  52.        ''' <param name="lpWindowName">The window name (the window's title).
  53.        ''' If this parameter is NULL, all window names match.</param>
  54.        ''' <returns>If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
  55.        ''' If the function fails, the return value is NULL.</returns>
  56.        <DllImport("user32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False)>
  57.        Friend Shared Function FindWindow(
  58.           ByVal lpClassName As String,
  59.           ByVal lpWindowName As String
  60.        ) As IntPtr
  61.        End Function
  62.  
  63.        ''' <summary>
  64.        ''' Retrieves a handle to a window whose class name and window name match the specified strings.
  65.        ''' The function searches child windows, beginning with the one following the specified child window.
  66.        ''' This function does not perform a case-sensitive search.
  67.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633500%28v=vs.85%29.aspx
  68.        ''' </summary>
  69.        ''' <param name="hwndParent">
  70.        ''' A handle to the parent window whose child windows are to be searched.
  71.        ''' If hwndParent is NULL, the function uses the desktop window as the parent window.
  72.        ''' The function searches among windows that are child windows of the desktop.
  73.        ''' </param>
  74.        ''' <param name="hwndChildAfter">
  75.        ''' A handle to a child window.
  76.        ''' The search begins with the next child window in the Z order.
  77.        ''' The child window must be a direct child window of hwndParent, not just a descendant window.
  78.        ''' If hwndChildAfter is NULL, the search begins with the first child window of hwndParent.
  79.        ''' </param>
  80.        ''' <param name="strClassName">
  81.        ''' The window class name.
  82.        ''' </param>
  83.        ''' <param name="strWindowName">
  84.        ''' The window name (the window's title).
  85.        ''' If this parameter is NULL, all window names match.
  86.        ''' </param>
  87.        ''' <returns>
  88.        ''' If the function succeeds, the return value is a handle to the window that has the specified class and window names.
  89.        ''' If the function fails, the return value is NULL.
  90.        ''' </returns>
  91.        <DllImport("User32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False)>
  92.        Friend Shared Function FindWindowEx(
  93.           ByVal hwndParent As IntPtr,
  94.           ByVal hwndChildAfter As IntPtr,
  95.           ByVal strClassName As String,
  96.           ByVal strWindowName As String
  97.        ) As IntPtr
  98.        End Function
  99.  
  100.        ''' <summary>
  101.        ''' Retrieves the identifier of the thread that created the specified window
  102.        ''' and, optionally, the identifier of the process that created the window.
  103.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633522%28v=vs.85%29.aspx
  104.        ''' </summary>
  105.        ''' <param name="hWnd">A handle to the window.</param>
  106.        ''' <param name="ProcessId">
  107.        ''' A pointer to a variable that receives the process identifier.
  108.        ''' If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the variable;
  109.        ''' otherwise, it does not.
  110.        ''' </param>
  111.        ''' <returns>The identifier of the thread that created the window.</returns>
  112.        <DllImport("user32.dll")>
  113.        Friend Shared Function GetWindowThreadProcessId(
  114.            ByVal hWnd As IntPtr,
  115.            ByRef ProcessId As Integer
  116.        ) As Integer
  117.        End Function
  118.  
  119.        ''' <summary>
  120.        ''' Sets the specified window's show state.
  121.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
  122.        ''' </summary>
  123.        ''' <param name="hwnd">A handle to the window.</param>
  124.        ''' <param name="nCmdShow">Controls how the window is to be shown.</param>
  125.        ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  126.        <DllImport("User32", SetLastError:=False)>
  127.        Friend Shared Function ShowWindow(
  128.           ByVal hwnd As IntPtr,
  129.           ByVal nCmdShow As WindowState
  130.        ) As Boolean
  131.        End Function
  132.  
  133. #End Region
  134.  
  135.    End Class
  136.  
  137. #End Region
  138.  
  139. #Region " Enumerations "
  140.  
  141.    ''' <summary>
  142.    ''' Controls how the window is to be shown.
  143.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
  144.    ''' </summary>
  145.    Friend Enum WindowState As Integer
  146.  
  147.        ''' <summary>
  148.        ''' Hides the window and activates another window.
  149.        ''' </summary>
  150.        Hide = 0I
  151.  
  152.        ''' <summary>
  153.        ''' Activates and displays a window.
  154.        ''' If the window is minimized or maximized, the system restores it to its original size and position.
  155.        ''' An application should specify this flag when displaying the window for the first time.
  156.        ''' </summary>
  157.        Normal = 1I
  158.  
  159.        ''' <summary>
  160.        ''' Activates the window and displays it as a minimized window.
  161.        ''' </summary>
  162.        ShowMinimized = 2I
  163.  
  164.        ''' <summary>
  165.        ''' Maximizes the specified window.
  166.        ''' </summary>
  167.        Maximize = 3I
  168.  
  169.        ''' <summary>
  170.        ''' Activates the window and displays it as a maximized window.
  171.        ''' </summary>      
  172.        ShowMaximized = Maximize
  173.  
  174.        ''' <summary>
  175.        ''' Displays a window in its most recent size and position.
  176.        ''' This value is similar to <see cref="WindowState.Normal"/>, except the window is not actived.
  177.        ''' </summary>
  178.        ShowNoActivate = 4I
  179.  
  180.        ''' <summary>
  181.        ''' Activates the window and displays it in its current size and position.
  182.        ''' </summary>
  183.        Show = 5I
  184.  
  185.        ''' <summary>
  186.        ''' Minimizes the specified window and activates the next top-level window in the Z order.
  187.        ''' </summary>
  188.        Minimize = 6I
  189.  
  190.        ''' <summary>
  191.        ''' Displays the window as a minimized window.
  192.        ''' This value is similar to <see cref="WindowState.ShowMinimized"/>, except the window is not activated.
  193.        ''' </summary>
  194.        ShowMinNoActive = 7I
  195.  
  196.        ''' <summary>
  197.        ''' Displays the window in its current size and position.
  198.        ''' This value is similar to <see cref="WindowState.Show"/>, except the window is not activated.
  199.        ''' </summary>
  200.        ShowNA = 8I
  201.  
  202.        ''' <summary>
  203.        ''' Activates and displays the window.
  204.        ''' If the window is minimized or maximized, the system restores it to its original size and position.
  205.        ''' An application should specify this flag when restoring a minimized window.
  206.        ''' </summary>
  207.        Restore = 9I
  208.  
  209.        ''' <summary>
  210.        ''' Sets the show state based on the SW_* value specified in the STARTUPINFO structure
  211.        ''' passed to the CreateProcess function by the program that started the application.
  212.        ''' </summary>
  213.        ShowDefault = 10I
  214.  
  215.        ''' <summary>
  216.        ''' <b>Windows 2000/XP:</b>
  217.        ''' Minimizes a window, even if the thread that owns the window is not responding.
  218.        ''' This flag should only be used when minimizing windows from a different thread.
  219.        ''' </summary>
  220.        ForceMinimize = 11I
  221.  
  222.    End Enum
  223.  
  224. #End Region
  225.  
  226. #Region " Public Methods "
  227.  
  228.    ''' <summary>
  229.    ''' Set the state of a window by an HWND.
  230.    ''' </summary>
  231.    ''' <param name="WindowHandle">A handle to the window.</param>
  232.    ''' <param name="WindowState">The state of the window.</param>
  233.    ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  234.    Friend Shared Function SetWindowState(ByVal WindowHandle As IntPtr,
  235.                                          ByVal WindowState As WindowState) As Boolean
  236.  
  237.        Return NativeMethods.ShowWindow(WindowHandle, WindowState)
  238.  
  239.    End Function
  240.  
  241.    ''' <summary>
  242.    ''' Set the state of a window by a process name.
  243.    ''' </summary>
  244.    ''' <param name="ProcessName">The name of the process.</param>
  245.    ''' <param name="WindowState">The state of the window.</param>
  246.    ''' <param name="Recursivity">If set to <c>false</c>, only the first process instance will be processed.</param>
  247.    Friend Shared Sub SetWindowState(ByVal ProcessName As String,
  248.                                     ByVal WindowState As WindowState,
  249.                                     Optional ByVal Recursivity As Boolean = False)
  250.  
  251.        If ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
  252.            ProcessName = ProcessName.Remove(ProcessName.Length - ".exe".Length)
  253.        End If
  254.  
  255.        Dim pHandle As IntPtr = IntPtr.Zero
  256.        Dim pID As Integer = 0I
  257.  
  258.        Dim Processes As Process() = Process.GetProcessesByName(ProcessName)
  259.  
  260.        ' If any process matching the name is found then...
  261.        If Processes.Count = 0 Then
  262.            Exit Sub
  263.        End If
  264.  
  265.        For Each p As Process In Processes
  266.  
  267.            ' If Window is visible then...
  268.            If p.MainWindowHandle <> IntPtr.Zero Then
  269.                SetWindowState(p.MainWindowHandle, WindowState)
  270.  
  271.            Else ' Window is hidden
  272.  
  273.                ' Check all open windows (not only the process we are looking),
  274.                ' begining from the child of the desktop, phandle = IntPtr.Zero initialy.
  275.                While pID <> p.Id ' Check all windows.
  276.  
  277.                    ' Get child handle of window who's handle is "pHandle".
  278.                    pHandle = NativeMethods.FindWindowEx(IntPtr.Zero, pHandle, Nothing, Nothing)
  279.  
  280.                    ' Get ProcessId from "pHandle".
  281.                    NativeMethods.GetWindowThreadProcessId(pHandle, pID)
  282.  
  283.                    ' If the ProcessId matches the "pID" then...
  284.                    If pID = p.Id Then
  285.  
  286.                        NativeMethods.ShowWindow(pHandle, WindowState)
  287.  
  288.                        If Not Recursivity Then
  289.                            Exit For
  290.                        End If
  291.  
  292.                    End If
  293.  
  294.                End While
  295.  
  296.            End If
  297.  
  298.        Next p
  299.  
  300.    End Sub
  301.  
  302. #End Region
  303.  
  304. End Class
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #438 en: 3 Octubre 2014, 01:48 am »

Como obtener la ruta completa de los directorios de la barra de dirección de cada instancia de Windows Explorer (explorer.exe)

Código
  1.    ' ( By Elektro )
  2.    '
  3.    ' Instructions:
  4.    ' 1. Add a reference to 'Microsoft Shell Controls and Automation'
  5.    '
  6.    ' Usage Examples:
  7.    ' Dim paths As List(Of String) = GetWindowsExplorerPaths()
  8.    '
  9.    ''' <summary>
  10.    ''' Gets the full-path in the adressbar of each Windows Explorer instance.
  11.    ''' MSDN Shell Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776890%28v=vs.85%29.aspx
  12.    ''' </summary>
  13.    ''' <returns>A list containing the paths.</returns>
  14.    Friend Shared Function GetWindowsExplorerPaths() As List(Of String)
  15.  
  16.        Dim exShell As New Shell32.Shell
  17.        Dim folder As Shell32.Folder
  18.        Dim path As String
  19.        Dim pathList As New List(Of String)
  20.  
  21.        For Each Window As SHDocVw.ShellBrowserWindow In DirectCast(exShell.Windows, SHDocVw.IShellWindows)
  22.  
  23.            folder = DirectCast(Window.Document, Shell32.ShellFolderView).Folder
  24.            path = DirectCast(folder, Shell32.Folder2).Self.Path
  25.            pathList.Add(path)
  26.  
  27.        Next Window
  28.  
  29.        Return pathList
  30.  
  31.    End Function

PD: Lo mismo quizás se pueda llevar a cabo con la librería WindowsAPICodePack de Microsoft, le echaré un ojo...
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Librería de Snippets !! (Compartan aquí sus snippets)
« Respuesta #439 en: 3 Octubre 2014, 03:11 am »

Como implementar en menos de 5 segundos: un ComboBox para cambiar la prioridad del proceso actual.

Nota: Se puede hacer de manera más directa sin asignar los nombres, pero entonces perderiamos el orden de prioridad de menor a mayor.

Código
  1. Public Class PriorityList_TestForm
  2.  
  3.    ''' <summary>
  4.    ''' Contains the process priority items.  
  5.    ''' </summary>
  6.    Private ReadOnly PriorityList As String() =
  7.    {
  8.        ProcessPriorityClass.Idle.ToString,
  9.        ProcessPriorityClass.BelowNormal.ToString,
  10.        ProcessPriorityClass.Normal.ToString,
  11.        ProcessPriorityClass.AboveNormal.ToString,
  12.        ProcessPriorityClass.High.ToString,
  13.        ProcessPriorityClass.RealTime.ToString
  14.    }
  15.  
  16.    ''' <summary>
  17.    ''' Handles the Load event of the PriorityList_TestForm Form.
  18.    ''' </summary>
  19.    Private Shadows Sub Load() Handles MyBase.Load
  20.  
  21.        ' Add the priority items to list.
  22.        Me.ComboBox1.Items.AddRange(Me.PriorityList)
  23.  
  24.    End Sub
  25.  
  26.    ''' <summary>
  27.    ''' Handles the SelectedIndexChanged event of the ComboBox1 control.
  28.    ''' </summary>
  29.    ''' <param name="sender">The source of the event.</param>
  30.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  31.    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) _
  32.    Handles ComboBox1.SelectedIndexChanged
  33.  
  34.        ' Change thecurrent  process priority.
  35.        Process.GetCurrentProcess.PriorityClass =
  36.            [Enum].Parse(GetType(ProcessPriorityClass),
  37.                         DirectCast(sender, ComboBox).Text,
  38.                         ignoreCase:=True)
  39.  
  40.    End Sub
  41.  
  42. End Class




Lo mismo, pero usando Telerik:

Código
  1. Imports Telerik.WinControls.UI
  2. Imports Telerik.WinControls.UI.Data
  3.  
  4. Public Class PriorityList_RadTestForm
  5.  
  6.    ''' <summary>
  7.    ''' Contains the process priority items.  
  8.    ''' </summary>
  9.    Private ReadOnly PriorityList As New List(Of RadListDataItem) From
  10.    {
  11.        New RadListDataItem With {
  12.            .Text = ProcessPriorityClass.Idle.ToString,
  13.            .Value = ProcessPriorityClass.Idle
  14.        },
  15.        New RadListDataItem With {
  16.            .Text = ProcessPriorityClass.BelowNormal.ToString,
  17.            .Value = ProcessPriorityClass.BelowNormal
  18.        },
  19.        New RadListDataItem With {
  20.            .Text = ProcessPriorityClass.Normal.ToString,
  21.            .Value = ProcessPriorityClass.Normal
  22.        },
  23.        New RadListDataItem With {
  24.            .Text = ProcessPriorityClass.AboveNormal.ToString,
  25.            .Value = ProcessPriorityClass.AboveNormal
  26.        },
  27.        New RadListDataItem With {
  28.            .Text = ProcessPriorityClass.High.ToString,
  29.            .Value = ProcessPriorityClass.High
  30.        },
  31.        New RadListDataItem With {
  32.            .Text = ProcessPriorityClass.RealTime.ToString,
  33.            .Value = ProcessPriorityClass.RealTime
  34.        }
  35.    }
  36.  
  37.    ''' <summary>
  38.    ''' Handles the Initialized event of the RadDropDownList1 control.
  39.    ''' </summary>
  40.    ''' <param name="sender">The source of the event.</param>
  41.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  42.    Private Sub RadDropDownList1_Initialized(ByVal sender As Object, ByVal e As EventArgs) _
  43.    Handles RadDropDownList1.Initialized
  44.  
  45.        ' Add the priority items to list.
  46.        DirectCast(sender, RadDropDownList).Items.AddRange(PriorityList)
  47.  
  48.    End Sub
  49.  
  50.    ''' <summary>
  51.    ''' Handles the SelectedIndexChanged event of the RadDropDownList1 control.
  52.    ''' </summary>
  53.    ''' <param name="sender">The source of the event.</param>
  54.    ''' <param name="e">The <see cref="Telerik.WinControls.UI.Data.PositionChangedEventArgs"/> instance containing the event data.</param>
  55.    Private Sub RadDropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As PositionChangedEventArgs) _
  56.    Handles RadDropDownList1.SelectedIndexChanged
  57.  
  58.        ' Change thecurrent  process priority.
  59.        Process.GetCurrentProcess.PriorityClass =
  60.            DirectCast(DirectCast(sender, RadDropDownList).SelectedItem.Value, ProcessPriorityClass)
  61.  
  62.    End Sub
  63.  
  64. End Class
« Última modificación: 3 Octubre 2014, 03:13 am por Eleкtro » En línea

Páginas: 1 ... 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 [44] 45 46 47 48 49 50 51 52 53 54 55 56 57 58 Ir Arriba Respuesta Imprimir 

Ir a:  

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