Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

Iniciado por Eleкtro, 18 Diciembre 2012, 22:23 PM

0 Miembros y 1 Visitante están viendo este tema.

Eleкtro

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 (vbnet) [Seleccionar]

    ' Add Watermark
    ' By Elektro

    ''' <summary>
    ''' Adds a watermark into an image, at the specified position.
    ''' </summary>
    ''' <param name="img">Indicates the image.</param>
    ''' <param name="text">Indicates the watermark text.</param>
    ''' <param name="fnt">Indicates the watermark text font.</param>
    ''' <param name="color">Indicates the watermark text color.</param>
    ''' <param name="position">Indicates the watermark text position.</param>
    ''' <returns>Aspose.Imaging.Image.</returns>
    Private Function AddWatermark(ByVal img As Aspose.Imaging.Image,
                                  ByVal text As String,
                                  ByVal fnt As Aspose.Imaging.Font,
                                  ByVal color As Aspose.Imaging.Color,
                                  ByVal position As Aspose.Imaging.PointF) As Aspose.Imaging.Image

        Using brush As New Aspose.Imaging.Brushes.SolidBrush With {.Color = color, .Opacity = 100.0F}

            ' Create and initialize an instance of Graphics class.
            Dim g As New Aspose.Imaging.Graphics(img)

            ' Draw a String using the SolidBrush object and Font, at specific Point and with specific format.
            g.DrawString(s:=text, font:=fnt, brush:=brush, point:=position)

        End Using

        ' Return the modified image.
        Return img

    End Function

    ''' <summary>
    ''' Adds a watermark into an image, at a prefedined position.
    ''' </summary>
    ''' <param name="img">Indicates the image.</param>
    ''' <param name="text">Indicates the watermark text.</param>
    ''' <param name="fnt">Indicates the watermark text font.</param>
    ''' <param name="color">Indicates the watermark text color.</param>
    ''' <param name="position">Indicates the watermark text position.</param>
    ''' <param name="verticalmargin">Indicates the watermark text vertical margin.</param>
    ''' <param name="horizontalmargin">Indicates the watermark text horizontal margin.</param>
    ''' <returns>Aspose.Imaging.Image.</returns>
    Private Function AddWatermark(ByVal img As Aspose.Imaging.Image,
                                  ByVal text As String,
                                  ByVal fnt As Aspose.Imaging.Font,
                                  ByVal color As Aspose.Imaging.Color,
                                  ByVal position As WatermarkPosition,
                                  Optional ByVal verticalmargin As Single = 0.0F,
                                  Optional ByVal horizontalmargin As Single = 0.0F) As Aspose.Imaging.Image

        Dim textformat As New Aspose.Imaging.StringFormat
        Dim textposition As Aspose.Imaging.PointF = Aspose.Imaging.PointF.Empty
        textformat.FormatFlags = Aspose.Imaging.StringFormatFlags.MeasureTrailingSpaces

        Select Case position

            Case WatermarkPosition.Top ' Note: horizontalmargin value is ignored.
                textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=verticalmargin)
                textformat.Alignment = Aspose.Imaging.StringAlignment.Center

            Case WatermarkPosition.TopLeft
                textposition = New Aspose.Imaging.PointF(x:=horizontalmargin, y:=verticalmargin)
                textformat.Alignment = Aspose.Imaging.StringAlignment.Near

            Case WatermarkPosition.TopRight
                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
                textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=verticalmargin)
                textformat.Alignment = Aspose.Imaging.StringAlignment.Near

            Case WatermarkPosition.Middle ' Note: verticalmargin horizontalmargin and values are ignored.
                textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=(img.Height \ 2))
                textformat.Alignment = Aspose.Imaging.StringAlignment.Center

            Case WatermarkPosition.MiddleLeft ' Note: verticalmargin value is ignored.
                textposition = New Aspose.Imaging.PointF(x:=(horizontalmargin), y:=(img.Height \ 2))
                textformat.Alignment = Aspose.Imaging.StringAlignment.Near

            Case WatermarkPosition.MiddleRight ' Note: verticalmargin value is ignored.
                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
                textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=(img.Height \ 2))
                textformat.Alignment = Aspose.Imaging.StringAlignment.Near

            Case WatermarkPosition.Bottom ' Note: horizontalmargin value is ignored.
                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
                textposition = New Aspose.Imaging.PointF(x:=(img.Width \ 2), y:=(img.Height - measure.Height - verticalmargin))
                textformat.Alignment = Aspose.Imaging.StringAlignment.Center

            Case WatermarkPosition.BottomLeft
                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
                textposition = New Aspose.Imaging.PointF(x:=(horizontalmargin), y:=(img.Height - measure.Height - verticalmargin))
                textformat.Alignment = Aspose.Imaging.StringAlignment.Near

            Case WatermarkPosition.BottomRight
                Dim f As New System.Drawing.Font(fnt.Name, fnt.Size, DirectCast(fnt.Style, System.Drawing.FontStyle))
                Dim measure As System.Drawing.Size = TextRenderer.MeasureText(text, f)
                textposition = New Aspose.Imaging.PointF(x:=(img.Width - measure.Width - horizontalmargin), y:=(img.Height - measure.Height - verticalmargin))
                textformat.Alignment = Aspose.Imaging.StringAlignment.Near

        End Select

        Using brush As New Aspose.Imaging.Brushes.SolidBrush With {.Color = color, .Opacity = 100.0F}

            ' Create and initialize an instance of Graphics class.
            Dim g As New Aspose.Imaging.Graphics(img)

            ' Draw a String using the SolidBrush object and Font, at specific Point and with specific format.
            g.DrawString(s:=text, font:=fnt, brush:=brush, point:=textposition, format:=textformat)

        End Using

        textformat.Dispose()

        ' Return the modified image.
        Return img

    End Function

    ''' <summary>
    ''' Specifies a Watermark position
    ''' </summary>
    Public Enum WatermarkPosition As Short

        ''' <summary>
        ''' Top position.
        ''' horizontalmargin value is ignored.
        ''' </summary>
        Top = 0S

        ''' <summary>
        ''' Top-Left position.
        ''' </summary>
        TopLeft = 1S

        ''' <summary>
        ''' Top-Right position.
        ''' </summary>
        TopRight = 2S

        ''' <summary>
        ''' Middle-Left position.
        ''' verticalmargin value is ignored.
        ''' </summary>
        MiddleLeft = 3S

        ''' <summary>
        ''' Middle position.
        ''' verticalmargin and horizontalmargin values are ignored.
        ''' </summary>
        Middle = 4S

        ''' <summary>
        ''' Middle-Right position.
        ''' verticalmargin value is ignored.
        ''' </summary>
        MiddleRight = 5S

        ''' <summary>
        ''' Bottom position.
        ''' horizontalmargin value is ignored.
        ''' </summary>
        Bottom = 6S

        ''' <summary>
        ''' Bottom-Left position.
        ''' </summary>
        BottomLeft = 7S

        ''' <summary>
        ''' Bottom-Right position.
        ''' </summary>
        BottomRight = 8S

    End Enum


Ejemplo de uso:

Código (vbnet) [Seleccionar]
    Private Sub Form1_Load() Handles MyBase.Load

        ' Load an image to add a watermark.
        Dim img As Aspose.Imaging.Image = Aspose.Imaging.Image.Load("C:\sample.bmp")

        ' Set the watermark text.
        Dim text As String = "ElektroStudios"

        ' Set the watermark text color.
        Dim color As Aspose.Imaging.Color = Aspose.Imaging.Color.White

        ' Set the watermark text font.
        Dim fnt As New Aspose.Imaging.Font("Lucida Console", 32, FontStyle.Bold)

        ' Add the watermark into the image.
        img = Me.AddWatermark(img:=img, text:=text, fnt:=fnt, color:=color, position:=WatermarkPosition.BottomRight)

        ' Or...
        ' Dim position As New Aspose.Imaging.PointF(x:=10, y:=10)
        ' img = Me.AddWatermark(img:=img, text:=text, fnt:=fnt, color:=color, position:=position)

        ' Save the image to disk.
        img.Save("C:\Watermark.bmp")

        ' See the resulting image.
        Process.Start("C:\Watermark.bmp")
        Application.Exit()

    End Sub








Eleкtro

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 (vbnet) [Seleccionar]

    ''' <summary>
    ''' Flag that determines whether the user made a single click.
    ''' </summary>
    Private DidSingleClick As Boolean = False

    ''' <summary>
    ''' Flag that determines whether the user made a double click.
    ''' </summary>
    Private DidDoubleClick As Boolean = False

    ''' <summary>
    ''' Flag that determines whether the user made a triple click.
    ''' </summary>
    Private DidTripleclick As Boolean = False

    ''' <summary>
    ''' Timer that resets the click-count after an inactivity period.
    ''' </summary>
    Private WithEvents ClickInactivity_Timer As New Timer With
    {
        .Interval = SystemInformation.DoubleClickTime,
        .Enabled = False
    }

    ''' <summary>
    ''' Handles the MouseClick event of the TextBox1 control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
    Private Sub TextBox1_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs) _
    Handles TextBox1.MouseClick

        If Me.ClickInactivity_Timer.Enabled Then
            Me.ClickInactivity_Timer.Enabled = False
        End If

        Me.DidSingleClick = True

    End Sub

    ''' <summary>
    ''' Handles the MouseDoubleClick event of the TextBox1 control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
    Private Sub TextBox1_MouseDoubleClick(ByVal sender As Object, ByVal e As MouseEventArgs) _
    Handles TextBox1.MouseDoubleClick

        If Me.ClickInactivity_Timer.Enabled Then
            Me.ClickInactivity_Timer.Enabled = False
        End If

        Me.DidDoubleClick = True

    End Sub

    ''' <summary>
    ''' Handles the MouseUp event of the TextBox1 control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
    Private Sub TextBox1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) _
    Handles TextBox1.MouseUp

        If Not Me.ClickInactivity_Timer.Enabled Then

            Me.ClickInactivity_Timer.Enabled = True
            Me.ClickInactivity_Timer.Start()

        End If

    End Sub

    ''' <summary>
    ''' Handles the MouseDown event of the TextBox1 control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
    Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) _
    Handles TextBox1.MouseDown

        Me.DidTripleclick = (Me.DidDoubleClick AndAlso Me.DidSingleClick)

        If Me.DidTripleclick Then

            Me.DidSingleClick = False
            Me.DidDoubleClick = False
            Me.DidTripleclick = False

            sender.SelectAll()

        End If

    End Sub

    ''' <summary>
    ''' Handles the Tick event of the ClickInactivity_Timer control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    Private Sub ClickInactivity_Timer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
    Handles ClickInactivity_Timer.Tick

        Me.DidSingleClick = False
        Me.DidDoubleClick = False
        Me.DidTripleclick = False

        sender.Enabled = False

    End Sub








Eleкtro

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

Ejemplo de uso:

Código (vbnet) [Seleccionar]
Private WindowSticker As New WindowSticker(ClientForm:=Me) With {.SnapMargin = 35}


Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 09-19-2014
' ***********************************************************************
' <copyright file="WindowSticker.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

' Private WindowSticker As New WindowSticker(ClientForm:=Me) With {.SnapMargin = 35}

'Private Sub Form1_Load() Handles MyBase.Shown

'    WindowSticker.Dispose()
'    WindowSticker = New WindowSticker(Form2)
'    WindowSticker.ClientForm.Show()

'End Sub

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Runtime.InteropServices

#End Region

#Region " WindowSticker "

''' <summary>
''' Sticks a Form to a Desktop border (if the Form is near).
''' </summary>
Public Class WindowSticker : Inherits NativeWindow : Implements IDisposable

#Region " Properties "

#Region " Public "

    ''' <summary>
    ''' Gets the client form used to stick its borders.
    ''' </summary>
    ''' <value>The client form used to stick its borders.</value>
    Public ReadOnly Property ClientForm As Form
        Get
            Return Me._ClientForm
        End Get
    End Property
    Private WithEvents _ClientForm As Form = Nothing

    ''' <summary>
    ''' Gets or sets the snap margin (offset), in pixels.
    ''' (Default value is: 30))
    ''' </summary>
    ''' <value>The snap margin (offset), in pixels.</value>
    Public Property SnapMargin As Integer
        Get
            Return Me._SnapMargin
        End Get
        Set(ByVal value As Integer)
            Me.DisposedCheck()
            Me._SnapMargin = value
        End Set
    End Property
    Private _SnapMargin As Integer = 30I

#End Region

#Region " Private "

    ''' <summary>
    ''' Gets rectangle that contains the size of the current screen.
    ''' </summary>
    ''' <value>The rectangle that contains the size of the current screen.</value>
    Private ReadOnly Property ScreenRect As Rectangle
        Get
            Return Screen.FromControl(Me._ClientForm).Bounds
        End Get
    End Property

    ''' <summary>
    ''' Gets the working area of the current screen.
    ''' </summary>
    ''' <value>The working area of the current screen.</value>
    Private ReadOnly Property WorkingArea As Rectangle
        Get
            Return Screen.FromControl(Me._ClientForm).WorkingArea
        End Get
    End Property

    ''' <summary>
    ''' Gets the desktop taskbar height (when thet taskbar is horizontal).
    ''' </summary>
    ''' <value>The desktop taskbar height (when thet taskbar is horizontal).</value>
    Private ReadOnly Property TaskbarHeight As Integer
        Get
            Return Me.ScreenRect.Height - Me.WorkingArea.Height
        End Get
    End Property

#End Region

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Windows Message Identifiers.
    ''' </summary>
    <Description("Messages to process in WndProc")>
    Public Enum WindowsMessages As Integer

        ''' <summary>
        ''' Sent to a window whose size, position, or place in the Z order is about to change.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632653%28v=vs.85%29.aspx
        ''' </summary>
        WM_WINDOWPOSCHANGING = &H46I

    End Enum

#End Region

#Region " Structures "

    ''' <summary>
    ''' Contains information about the size and position of a window.
    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632612%28v=vs.85%29.aspx
    ''' </summary>
    <StructLayout(LayoutKind.Sequential)>
    Public Structure WINDOWPOS

        ''' <summary>
        ''' A handle to the window.
        ''' </summary>
        Public hwnd As IntPtr

        ''' <summary>
        ''' The position of the window in Z order (front-to-back position).
        ''' This member can be a handle to the window behind which this window is placed,
        ''' or can be one of the special values listed with the 'SetWindowPos' function.
        ''' </summary>
        Public hwndInsertAfter As IntPtr

        ''' <summary>
        ''' The position of the left edge of the window.
        ''' </summary>
        Public x As Integer

        ''' <summary>
        ''' The position of the top edge of the window.
        ''' </summary>
        Public y As Integer

        ''' <summary>
        ''' The window width, in pixels.
        ''' </summary>
        Public width As Integer

        ''' <summary>
        ''' The window height, in pixels.
        ''' </summary>
        Public height As Integer

        ''' <summary>
        ''' Flag containing the window position.
        ''' </summary>
        Public flags As Integer

    End Structure

#End Region

#Region " Constructor "

    ''' <summary>
    ''' Initializes a new instance of WindowSticker class.
    ''' </summary>
    ''' <param name="ClientForm">The client form to assign this NativeWindow.</param>
    Public Sub New(ByVal ClientForm As Form)

        ' Assign the Formulary.
        Me._ClientForm = ClientForm

    End Sub

    ''' <summary>
    ''' Prevents a default instance of the <see cref="WindowSticker"/> class from being created.
    ''' </summary>
    Private Sub New()
    End Sub

#End Region

#Region " Event Handlers "

    ''' <summary>
    ''' Assign the handle of the target Form to this NativeWindow,
    ''' necessary to override target Form's WndProc.
    ''' </summary>
    Private Sub SetFormHandle() Handles _ClientForm.HandleCreated, _ClientForm.Load, _ClientForm.Shown

        If (Me._ClientForm IsNot Nothing) AndAlso (Not MyBase.Handle.Equals(Me._ClientForm.Handle)) Then

            MyBase.AssignHandle(Me._ClientForm.Handle)

        End If

    End Sub

    ''' <summary>
    ''' Releases the Handle.
    ''' </summary>
    Private Sub OnHandleDestroyed() Handles _ClientForm.HandleDestroyed

        MyBase.ReleaseHandle()

    End Sub

#End Region

#Region " WndProc "

    ''' <summary>
    ''' Invokes the default window procedure associated with this window to process messages.
    ''' </summary>
    ''' <param name="m">
    ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
    ''' </param>
    Protected Overrides Sub WndProc(ByRef m As Message)

        If (Me._ClientForm IsNot Nothing) AndAlso (m.Msg = WindowsMessages.WM_WINDOWPOSCHANGING) Then

            Me.SnapToDesktopBorder(ClientForm:=Me._ClientForm, Handle:=m.LParam, widthAdjustment:=0)

        End If

        MyBase.WndProc(m)

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Sticks a Form to a desktop border (it its near).
    ''' </summary>
    ''' <param name="ClientForm">The client form used to stick its borders.</param>
    ''' <param name="Handle">A pointer to a 'WINDOWPOS' structure that contains information about the window's new size and position.</param>
    ''' <param name="widthAdjustment">The border width adjustment.</param>
    Private Sub SnapToDesktopBorder(ByVal ClientForm As Form,
                                    ByVal Handle As IntPtr,
                                    Optional ByVal widthAdjustment As Integer = 0I)

        Dim newPosition As WINDOWPOS = CType(Marshal.PtrToStructure(Handle, GetType(WINDOWPOS)), WINDOWPOS)

        If (newPosition.y = 0) OrElse (newPosition.x = 0) Then
            ' Nothing to do.
            Exit Sub
        End If

        ' Top border (check if taskbar is on top or bottom via WorkingRect.Y)
        If (newPosition.y >= -SnapMargin AndAlso (Me.WorkingArea.Y > 0 AndAlso newPosition.y <= (Me.TaskbarHeight + Me.SnapMargin))) _
        OrElse (Me.WorkingArea.Y <= 0 AndAlso newPosition.y <= (SnapMargin)) Then

            If Me.TaskbarHeight > 0 Then
                ' Horizontal Taskbar
                newPosition.y = Me.WorkingArea.Y
            Else
                ' Vertical Taskbar
                newPosition.y = 0
            End If

        End If

        ' Left border
        If (newPosition.x >= Me.WorkingArea.X - Me.SnapMargin) _
        AndAlso (newPosition.x <= Me.WorkingArea.X + Me.SnapMargin) Then

            newPosition.x = Me.WorkingArea.X

        End If

        ' Right border.
        If (newPosition.x + Me._ClientForm.Width <= Me.WorkingArea.Right + Me.SnapMargin) _
        AndAlso (newPosition.x + Me._ClientForm.Width >= Me.WorkingArea.Right - Me.SnapMargin) Then

            newPosition.x = (Me.WorkingArea.Right - Me._ClientForm.Width)

        End If

        ' Bottom border.
        If (newPosition.y + Me._ClientForm.Height <= Me.WorkingArea.Bottom + Me.SnapMargin) _
        AndAlso (newPosition.y + Me._ClientForm.Height >= Me.WorkingArea.Bottom - Me.SnapMargin) Then

            newPosition.y = (Me.WorkingArea.Bottom - Me._ClientForm.Height)

        End If

        ' Marshal it back.
        Marshal.StructureToPtr([structure]:=newPosition, ptr:=Handle, fDeleteOld:=True)

    End Sub

#End Region

#Region " Hidden Methods "

    ''' <summary>
    ''' Determines whether the specified System.Object instances are the same instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Private Shadows Sub ReferenceEquals()
    End Sub

    ''' <summary>
    ''' Assigns a handle to this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub AssignHandle()
    End Sub

    ''' <summary>
    ''' Creates a window and its handle with the specified creation parameters.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub CreateHandle()
    End Sub

    ''' <summary>
    ''' Destroys the window and its handle.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub DestroyHandle()
    End Sub

    ''' <summary>
    ''' Releases the handle associated with this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub ReleaseHandle()
    End Sub

    ''' <summary>
    ''' Retrieves the window associated with the specified handle.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Private Shadows Sub FromHandle()
    End Sub

    ''' <summary>
    ''' Serves as a hash function for a particular type.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub GetHashCode()
    End Sub

    ''' <summary>
    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function GetLifeTimeService()
        Return Nothing
    End Function

    ''' <summary>
    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function InitializeLifeTimeService()
        Return Nothing
    End Function

    ''' <summary>
    ''' Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function CreateObjRef()
        Return Nothing
    End Function

    ''' <summary>
    ''' Determines whether the specified System.Object instances are considered equal.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub Equals()
    End Sub

    ''' <summary>
    ''' Returns a String that represents the current object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub ToString()
    End Sub

    ''' <summary>
    ''' Invokes the default window procedure associated with this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub DefWndProc()
    End Sub

#End Region

#Region " IDisposable "

    ''' <summary>
    ''' To detect redundant calls when disposing.
    ''' </summary>
    Private IsDisposed As Boolean = False

    ''' <summary>
    ''' Prevent calls to methods after disposing.
    ''' </summary>
    ''' <exception cref="System.ObjectDisposedException"></exception>
    Private Sub DisposedCheck()

        If Me.IsDisposed Then
            Throw New ObjectDisposedException(Me.GetType().FullName)
        End If

    End Sub

    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' </summary>
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    ''' <summary>
    ''' Releases unmanaged and - optionally - managed resources.
    ''' </summary>
    ''' <param name="IsDisposing">
    ''' <c>true</c> to release both managed and unmanaged resources;
    ''' <c>false</c> to release only unmanaged resources.
    ''' </param>
    Protected Sub Dispose(ByVal IsDisposing As Boolean)

        If Not Me.IsDisposed Then

            If IsDisposing Then
                Me._ClientForm = Nothing
                MyBase.ReleaseHandle()
                MyBase.DestroyHandle()
            End If

        End If

        Me.IsDisposed = True

    End Sub

#End Region

End Class

#End Region








Eleкtro

#433
Ejecuta un applet del panel de control

ejemplo de uso:
Código (vbnet) [Seleccionar]
ControlPanelLauncher.Run(ControlPanelLauncher.Applets.SystemProperties)




Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 09-28-2014
' ***********************************************************************
' <copyright file="ControlPanelLauncher.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

' ControlPanelLauncher.Run()
' ControlPanelLauncher.RunApplet(ControlPanelLauncher.Applets.SystemProperties)

#End Region

''' <summary>
''' Runs a Windows Control Panel Applet.
''' Unofficial documentation: http://pcsupport.about.com/od/tipstricks/a/control-panel-command-line.htm
''' </summary>
Public Class ControlPanelLauncher

#Region " Constants/Readonly "

    ''' <summary>
    ''' The ControlPanel process location (control.exe)
    ''' </summary>
    Private Shared ReadOnly ControlProcess As String =
        IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "control.exe")

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Specifies a Control Panel Applet.
    ''' </summary>
    Public Enum Applets As Integer

        ''' <summary>
        ''' Action Center
        ''' </summary>
        ActionCenter

        ''' <summary>
        ''' Add Hardware
        ''' </summary>
        AddHardware

        ''' <summary>
        ''' Administrative Tools
        ''' </summary>
        AdministrativeTools

        ''' <summary>
        ''' AutoPlay
        ''' </summary>
        AutoPlay

        ''' <summary>
        ''' Backup And Restore
        ''' </summary>
        BackupAndRestore

        ''' <summary>
        ''' Biometric Devices
        ''' </summary>
        BiometricDevices

        ''' <summary>
        ''' BitLocker Drive Encryption
        ''' </summary>
        BitLockerDriveEncryption

        ''' <summary>
        ''' Bluetooth Devices
        ''' </summary>
        BluetoothDevices

        ''' <summary>
        ''' Color Management
        ''' </summary>
        ColorManagement

        ''' <summary>
        ''' Credential Manager
        ''' </summary>
        CredentialManager

        ''' <summary>
        ''' Date And Time
        ''' </summary>
        DateAndTime

        ''' <summary>
        ''' Default Location
        ''' </summary>
        DefaultLocation

        ''' <summary>
        ''' Default Programs
        ''' </summary>
        DefaultPrograms

        ''' <summary>
        ''' Desktop Gadgets
        ''' </summary>
        DesktopGadgets

        ''' <summary>
        ''' Device Manager
        ''' </summary>
        DeviceManager

        ''' <summary>
        ''' Devices And Printers
        ''' </summary>
        DevicesAndPrinters

        ''' <summary>
        ''' Display
        ''' </summary>
        Display

        ''' <summary>
        ''' EaseOfAccess Center
        ''' </summary>
        EaseOfAccessCenter

        ''' <summary>
        ''' Family Safety
        ''' </summary>
        FamilySafety

        ''' <summary>
        ''' File History
        ''' </summary>
        FileHistory

        ''' <summary>
        ''' FlashPlayer Settings Manager
        ''' </summary>
        FlashPlayerSettingsManager

        ''' <summary>
        ''' Folder Options
        ''' </summary>
        FolderOptions

        ''' <summary>
        ''' Fonts
        ''' </summary>
        Fonts

        ''' <summary>
        ''' Game Controllers
        ''' </summary>
        GameControllers

        ''' <summary>
        ''' Get Programs
        ''' </summary>
        GetPrograms

        ''' <summary>
        ''' Getting Started
        ''' </summary>
        GettingStarted

        ''' <summary>
        ''' Home Group
        ''' </summary>
        HomeGroup

        ''' <summary>
        ''' Indexing Options
        ''' </summary>
        IndexingOptions

        ''' <summary>
        ''' Infrared
        ''' </summary>
        Infrared

        ''' <summary>
        ''' Internet Options
        ''' </summary>
        InternetOptions

        ''' <summary>
        ''' iSCSI Initiator
        ''' </summary>
        iSCSIInitiator

        ''' <summary>
        ''' Keyboard
        ''' </summary>
        Keyboard

        ''' <summary>
        ''' Language
        ''' </summary>
        Language

        ''' <summary>
        ''' Location And Other Sensors
        ''' </summary>
        LocationAndOtherSensors

        ''' <summary>
        ''' Mouse
        ''' </summary>
        Mouse

        ''' <summary>
        ''' Network And Sharing Center
        ''' </summary>
        NetworkAndSharingCenter

        ''' <summary>
        ''' Network Connections
        ''' </summary>
        NetworkConnections

        ''' <summary>
        ''' Network Setup Wizard
        ''' </summary>
        NetworkSetupWizard

        ''' <summary>
        ''' Notification Area Icons
        ''' </summary>
        NotificationAreaIcons

        ''' <summary>
        ''' Offline Files
        ''' </summary>
        OfflineFiles

        ''' <summary>
        ''' Parental Controls
        ''' </summary>
        ParentalControls

        ''' <summary>
        ''' Pen And Input Devices
        ''' </summary>
        PenAndInputDevices

        ''' <summary>
        ''' Pen And Touch
        ''' </summary>
        PenAndTouch

        ''' <summary>
        ''' People Near Me
        ''' </summary>
        PeopleNearMe

        ''' <summary>
        ''' Performance Information And Tools
        ''' </summary>
        PerformanceInformationAndTools

        ''' <summary>
        ''' Personalization
        ''' </summary>
        Personalization

        ''' <summary>
        ''' Phone And Modem Options
        ''' </summary>
        PhoneAndModemOptions

        ''' <summary>
        ''' Phone And Modem
        ''' </summary>
        PhoneAndModem

        ''' <summary>
        ''' Power Options
        ''' </summary>
        PowerOptions

        ''' <summary>
        ''' Printers And Faxes
        ''' </summary>
        PrintersAndFaxes

        ''' <summary>
        ''' Problem Reports And Solutions
        ''' </summary>
        ProblemReportsAndSolutions

        ''' <summary>
        ''' Programs And Features
        ''' </summary>
        ProgramsAndFeatures

        ''' <summary>
        ''' Recovery
        ''' </summary>
        Recovery

        ''' <summary>
        ''' Region And Language
        ''' </summary>
        RegionAndLanguage

        ''' <summary>
        ''' Regional And Language Options
        ''' </summary>
        RegionalAndLanguageOptions

        ''' <summary>
        ''' Remote App And Desktop Connections
        ''' </summary>
        RemoteAppAndDesktopConnections

        ''' <summary>
        ''' Scanners And Cameras
        ''' </summary>
        ScannersAndCameras

        ''' <summary>
        ''' Screen Resolution
        ''' </summary>
        ScreenResolution

        ''' <summary>
        ''' Security Center
        ''' </summary>
        SecurityCenter

        ''' <summary>
        ''' Sound
        ''' </summary>
        Sound

        ''' <summary>
        ''' Speech Recognition Options
        ''' </summary>
        SpeechRecognitionOptions

        ''' <summary>
        ''' Speech Recognition
        ''' </summary>
        SpeechRecognition

        ''' <summary>
        ''' Storage Spaces
        ''' </summary>
        StorageSpaces

        ''' <summary>
        ''' Sync Center
        ''' </summary>
        SyncCenter

        ''' <summary>
        ''' System
        ''' </summary>
        System

        ''' <summary>
        ''' System Properties
        ''' </summary>
        SystemProperties

        ''' <summary>
        ''' TabletPC Settings
        ''' </summary>
        TabletPCSettings

        ''' <summary>
        ''' Task Scheduler
        ''' </summary>
        TaskScheduler

        ''' <summary>
        ''' Taskbar
        ''' </summary>
        Taskbar

        ''' <summary>
        ''' Taskbar And StartMenu
        ''' </summary>
        TaskbarAndStartMenu

        ''' <summary>
        ''' Text To Speech
        ''' </summary>
        TextToSpeech

        ''' <summary>
        ''' Troubleshooting
        ''' </summary>
        Troubleshooting

        ''' <summary>
        ''' User Accounts
        ''' </summary>
        UserAccounts

        ''' <summary>
        ''' Welcome Center
        ''' </summary>
        WelcomeCenter

        ''' <summary>
        ''' Windows Anytime Upgrade
        ''' </summary>
        WindowsAnytimeUpgrade

        ''' <summary>
        ''' Windows CardSpace
        ''' </summary>
        WindowsCardSpace

        ''' <summary>
        ''' Windows Defender
        ''' </summary>
        WindowsDefender

        ''' <summary>
        ''' Windows Firewall
        ''' </summary>
        WindowsFirewall

        ''' <summary>
        ''' Windows Marketplace
        ''' </summary>
        WindowsMarketplace

        ''' <summary>
        ''' Windows Mobility Center
        ''' </summary>
        WindowsMobilityCenter

        ''' <summary>
        ''' Windows Sidebar Properties
        ''' </summary>
        WindowsSidebarProperties

        ''' <summary>
        ''' Windows SideShow
        ''' </summary>
        WindowsSideShow

        ''' <summary>
        ''' Windows Update
        ''' </summary>
        WindowsUpdate

    End Enum

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Runs the Control Panel.
    ''' </summary>
    Public Shared Sub Run()

        Process.Start(ControlProcess)

    End Sub

    ''' <summary>
    ''' Runs a Control Panel Applet.
    ''' </summary>
    ''' <param name="Applet">The applet.</param>
    Public Shared Sub RunApplet(ByVal Applet As Applets)

        Select Case Applet

            Case Applets.ActionCenter
                Process.Start(ControlProcess, "/name Microsoft.ActionCenter")

            Case Applets.AddHardware
                Process.Start(ControlProcess, "/name Microsoft.AddHardware")

            Case Applets.AdministrativeTools
                Process.Start(ControlProcess, "/name Microsoft.AdministrativeTools")

            Case Applets.AutoPlay
                Process.Start(ControlProcess, "/name Microsoft.AutoPlay")

            Case Applets.BackupAndRestore
                Process.Start(ControlProcess, "/name Microsoft.BackupAndRestore")

            Case Applets.BiometricDevices
                Process.Start(ControlProcess, "/name Microsoft.BiometricDevices")

            Case Applets.BitLockerDriveEncryption
                Process.Start(ControlProcess, "/name Microsoft.BitLockerDriveEncryption")

            Case Applets.BluetoothDevices
                Process.Start(ControlProcess, "/name Microsoft.BluetoothDevices")

            Case Applets.ColorManagement
                Process.Start(ControlProcess, "/name Microsoft.ColorManagement")

            Case Applets.CredentialManager
                Process.Start(ControlProcess, "/name Microsoft.CredentialManager")

            Case Applets.DateAndTime
                Process.Start(ControlProcess, "/name Microsoft.DateAndTime")

            Case Applets.DefaultLocation
                Process.Start(ControlProcess, "/name Microsoft.DefaultLocation")

            Case Applets.DefaultPrograms
                Process.Start(ControlProcess, "/name Microsoft.DefaultPrograms")

            Case Applets.DesktopGadgets
                Process.Start(ControlProcess, "/name Microsoft.DesktopGadgets")

            Case Applets.DeviceManager
                Process.Start(ControlProcess, "/name Microsoft.DeviceManager")

            Case Applets.DevicesAndPrinters
                Process.Start(ControlProcess, "/name Microsoft.DevicesAndPrinters")

            Case Applets.Display
                Process.Start(ControlProcess, "/name Microsoft.Display")

            Case Applets.EaseOfAccessCenter
                Process.Start(ControlProcess, "/name Microsoft.EaseOfAccessCenter")

            Case Applets.FamilySafety
                Process.Start(ControlProcess, "/name Microsoft.ParentalControls")

            Case Applets.FileHistory
                Process.Start(ControlProcess, "/name Microsoft.FileHistory")

            Case Applets.FlashPlayerSettingsManager
                Process.Start(ControlProcess, "flashplayercplapp.cpl")

            Case Applets.FolderOptions
                Process.Start(ControlProcess, "/name Microsoft.FolderOptions")

            Case Applets.Fonts
                Process.Start(ControlProcess, "/name Microsoft.Fonts")

            Case Applets.GameControllers
                Process.Start(ControlProcess, "/name Microsoft.GameControllers")

            Case Applets.GetPrograms
                Process.Start(ControlProcess, "/name Microsoft.GetPrograms")

            Case Applets.GettingStarted
                Process.Start(ControlProcess, "/name Microsoft.GettingStarted")

            Case Applets.HomeGroup
                Process.Start(ControlProcess, "/name Microsoft.HomeGroup")

            Case Applets.IndexingOptions
                Process.Start(ControlProcess, "/name Microsoft.IndexingOptions")

            Case Applets.Infrared
                Process.Start(ControlProcess, "/name Microsoft.Infrared")

            Case Applets.InternetOptions
                Process.Start(ControlProcess, "/name Microsoft.InternetOptions")

            Case Applets.iSCSIInitiator
                Process.Start(ControlProcess, "/name Microsoft.iSCSIInitiator")

            Case Applets.Keyboard
                Process.Start(ControlProcess, "/name Microsoft.Keyboard")

            Case Applets.Language
                Process.Start(ControlProcess, "/name Microsoft.Language")

            Case Applets.LocationAndOtherSensors
                Process.Start(ControlProcess, "/name Microsoft.LocationAndOtherSensors")

            Case Applets.Mouse
                Process.Start(ControlProcess, "/name Microsoft.Mouse")

            Case Applets.NetworkAndSharingCenter
                Process.Start(ControlProcess, "/name Microsoft.NetworkAndSharingCenter")

            Case Applets.NetworkConnections
                Process.Start(ControlProcess, "ncpa.cpl")

            Case Applets.NetworkSetupWizard
                Process.Start(ControlProcess, "netsetup.cpl")

            Case Applets.NotificationAreaIcons
                Process.Start(ControlProcess, "/name Microsoft.NotificationAreaIcons")

            Case Applets.OfflineFiles
                Process.Start(ControlProcess, "/name Microsoft.OfflineFiles")

            Case Applets.ParentalControls
                Process.Start(ControlProcess, "/name Microsoft.ParentalControls")

            Case Applets.PenAndInputDevices
                Process.Start(ControlProcess, "/name Microsoft.PenAndInputDevices")

            Case Applets.PenAndTouch
                Process.Start(ControlProcess, "/name Microsoft.PenAndTouch")

            Case Applets.PeopleNearMe
                Process.Start(ControlProcess, "/name Microsoft.PeopleNearMe")

            Case Applets.PerformanceInformationAndTools
                Process.Start(ControlProcess, "/name Microsoft.PerformanceInformationAndTools")

            Case Applets.Personalization
                Process.Start(ControlProcess, "/name Microsoft.Personalization")

            Case Applets.PhoneAndModemOptions
                Process.Start(ControlProcess, "/name Microsoft.PhoneAndModemOptions")

            Case Applets.PhoneAndModem
                Process.Start(ControlProcess, "/name Microsoft.PhoneAndModem")

            Case Applets.PowerOptions
                Process.Start(ControlProcess, "/name Microsoft.PowerOptions")

            Case Applets.PrintersAndFaxes
                Process.Start(ControlProcess, "/name Microsoft.Printers")

            Case Applets.ProblemReportsAndSolutions
                Process.Start(ControlProcess, "/name Microsoft.ProblemReportsAndSolutions")

            Case Applets.ProgramsAndFeatures
                Process.Start(ControlProcess, "/name Microsoft.ProgramsAndFeatures")

            Case Applets.Recovery
                Process.Start(ControlProcess, "/name Microsoft.Recovery")

            Case Applets.RegionAndLanguage
                Process.Start(ControlProcess, "/name Microsoft.RegionAndLanguage")

            Case Applets.RegionalAndLanguageOptions
                Process.Start(ControlProcess, "/name Microsoft.RegionalAndLanguageOptions")

            Case Applets.RemoteAppAndDesktopConnections
                Process.Start(ControlProcess, "/name Microsoft.RemoteAppAndDesktopConnections")

            Case Applets.ScannersAndCameras
                Process.Start(ControlProcess, "/name Microsoft.ScannersAndCameras")

            Case Applets.ScreenResolution
                Process.Start(ControlProcess, "desk.cpl")

            Case Applets.SecurityCenter
                Process.Start(ControlProcess, "/name Microsoft.SecurityCenter")

            Case Applets.Sound
                Process.Start(ControlProcess, "/name Microsoft.Sound")

            Case Applets.SpeechRecognitionOptions
                Process.Start(ControlProcess, "/name Microsoft.SpeechRecognitionOptions")

            Case Applets.SpeechRecognition
                Process.Start(ControlProcess, "/name Microsoft.SpeechRecognition")

            Case Applets.StorageSpaces
                Process.Start(ControlProcess, "/name Microsoft.StorageSpaces")

            Case Applets.SyncCenter
                Process.Start(ControlProcess, "/name Microsoft.SyncCenter")

            Case Applets.System
                Process.Start(ControlProcess, "/name Microsoft.System")

            Case Applets.SystemProperties
                Process.Start(ControlProcess, "sysdm.cpl")

            Case Applets.TabletPCSettings
                Process.Start(ControlProcess, "/name Microsoft.TabletPCSettings")

            Case Applets.TaskScheduler
                Process.Start(ControlProcess, "schedtasks")

            Case Applets.Taskbar
                Process.Start(ControlProcess, "/name Microsoft.Taskbar")

            Case Applets.TaskbarAndStartMenu
                Process.Start(ControlProcess, "/name Microsoft.TaskbarAndStartMenu")

            Case Applets.TextToSpeech
                Process.Start(ControlProcess, "/name Microsoft.TextToSpeech")

            Case Applets.Troubleshooting
                Process.Start(ControlProcess, "/name Microsoft.Troubleshooting")

            Case Applets.UserAccounts
                Process.Start(ControlProcess, "/name Microsoft.UserAccounts")

            Case Applets.WelcomeCenter
                Process.Start(ControlProcess, "/name Microsoft.WelcomeCenter")

            Case Applets.WindowsAnytimeUpgrade
                Process.Start(ControlProcess, "/name Microsoft.WindowsAnytimeUpgrade")

            Case Applets.WindowsCardSpace
                Process.Start(ControlProcess, "/name Microsoft.CardSpace")

            Case Applets.WindowsDefender
                Process.Start(ControlProcess, "/name Microsoft.WindowsDefender")

            Case Applets.WindowsFirewall
                Process.Start(ControlProcess, "/name Microsoft.WindowsFirewall")

            Case Applets.WindowsMarketplace
                Process.Start(ControlProcess, "/name Microsoft.GetProgramsOnline")

            Case Applets.WindowsMobilityCenter
                Process.Start(ControlProcess, "/name Microsoft.MobilityCenter")

            Case Applets.WindowsSidebarProperties
                Process.Start(ControlProcess, "/name Microsoft.WindowsSidebarProperties")

            Case Applets.WindowsSideShow
                Process.Start(ControlProcess, "/name Microsoft.WindowsSideShow")

            Case Applets.WindowsUpdate
                Process.Start(ControlProcess, "/name Microsoft.WindowsUpdate")

        End Select

    End Sub

#End Region

End Class









Eleкtro

#434
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 (vbnet) [Seleccionar]
Public Class form1

   ''' <summary>
   ''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
   ''' </summary>
   Private WithEvents Clock As New TimeMeasurer With {.UpdateInterval = 100}

   Private ctrl_ElapsedTime As Control ' Control used to display the time elapsed interval.
   Private ctrl_RemainingTime As Control ' Control used to display the time remaining interval.

   Private Shadows Sub Load() Handles MyBase.Load

       ctrl_ElapsedTime = Label1
       ctrl_RemainingTime = Label2

       Me.Clock.Start(60000) ' Measure 1 minute

       ' Or...
       ' Me.Clock.Stop() ' Stop temporally the time interval measurement.
       ' Me.Clock.Resume() ' Resume a previouslly stopped time interval measurement.
       ' Dim ClockState As TimeMeasurer.TimeMeasurerState = Me.Clock.State ' Get the state.

   End Sub

   Private Sub Clock_ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
   Handles Clock.ElapsedTimeUpdated

       ' Measure H:M:S:MS
       ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
                                             e.Hour, e.Minute, e.Second, e.Millisecond)

   End Sub

   Private Sub Clock_RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
   Handles Clock.RemainingTimeUpdated

       ' Measure H:M:S:MS
       ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
                                               e.Hour, e.Minute, e.Second, e.Millisecond)

       '' Measure H:M:S
       'ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
       '                                        e.Hour, e.Minute, e.Second + 1)

   End Sub

   Private Sub Clock_ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
   Handles Clock.ElapsedTimeFinished

       ' Measure H:M:S:MS
       ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
                                             e.Hour, e.Minute, e.Second, e.Millisecond)

   End Sub

   Private Sub Clock_RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
   Handles Clock.RemainingTimeFinished

       ' Measure H:M:S:MS
       ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
                                               e.Hour, e.Minute, e.Second, e.Millisecond)

   End Sub

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 (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 10-02-2014
' ***********************************************************************
' <copyright file="TimeMeasurer.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

'Public Class TimeMeasurer_Test
'
'    ''' <summary>
'    ''' The <see cref="TimeMeasurer"/> instance that measure time intervals.
'    ''' </summary>
'    Private WithEvents Clock As New TimeMeasurer With {.UpdateInterval = 100}
'
'    Private ctrl_ElapsedTime As Control ' Control used to display the time elapsed interval.
'    Private ctrl_RemainingTime As Control ' Control used to display the time remaining interval.
'
'    Private Shadows Sub Load() Handles MyBase.Load
'
'        ctrl_ElapsedTime = LabelElapsed
'        ctrl_RemainingTime = LabelRemaining
'
'        Me.Clock.Start(60000) ' Measure 1 minute
'
'        ' Or...
'        ' Me.Clock.Stop() ' Stop temporally the time interval measurement.
'        ' Me.Clock.Resume() ' Resume a previouslly stopped time interval measurement.
'        ' Dim ClockState As TimeMeasurer.TimeMeasurerState = Me.Clock.State ' Get the state.
'
'    End Sub
'
'    ''' <summary>
'    ''' Handles the ElapsedTimeUpdated event of the Clock instance.
'    ''' </summary>
'    ''' <param name="sender">The source of the event.</param>
'    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
'    Private Sub Clock_ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
'    Handles Clock.ElapsedTimeUpdated
'
'        ' Measure H:M:S:MS
'        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
'                                              e.Hour, e.Minute, e.Second, e.Millisecond)
'
'        ' Measure H:M:S
'        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
'                                              e.Hour, e.Minute, e.Second)
'
'    End Sub
'
'    ''' <summary>
'    ''' Handles the RemainingTimeUpdated event of the Clock instance.
'    ''' </summary>
'    ''' <param name="sender">The source of the event.</param>
'    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
'    Private Sub Clock_RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
'    Handles Clock.RemainingTimeUpdated
'
'        ' Measure H:M:S:MS
'        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
'                                                e.Hour, e.Minute, e.Second, e.Millisecond)
'
'        ' Measure H:M:S
'        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
'                                                e.Hour, e.Minute, e.Second + 1)
'
'    End Sub
'
'    ''' <summary>
'    ''' Handles the ElapsedTimeFinished event of the Clock instance.
'    ''' </summary>
'    ''' <param name="sender">The source of the event.</param>
'    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
'    Private Sub Clock_ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
'    Handles Clock.ElapsedTimeFinished
'
'        ' Measure H:M:S:MS
'        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
'                                              e.Hour, e.Minute, e.Second, e.Millisecond)
'
'        ' Measure H:M:S
'        ctrl_ElapsedTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
'                                              e.Hour, e.Minute, e.Second)
'
'    End Sub
'
'    ''' <summary>
'    ''' Handles the RemainingTimeFinished event of the Clock instance.
'    ''' </summary>
'    ''' <param name="sender">The source of the event.</param>
'    ''' <param name="e">The <see cref="TimeMeasurer.TimeMeasureEventArgs"/> instance containing the event data.</param>
'    Private Sub Clock_RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasurer.TimeMeasureEventArgs) _
'    Handles Clock.RemainingTimeFinished
'
'        ' Measure H:M:S:MS
'        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}",
'                                                e.Hour, e.Minute, e.Second, e.Millisecond)
'
'        ' Measure H:M:S
'        ctrl_RemainingTime.Text = String.Format("{0:00}:{1:00}:{2:00}",
'                                                e.Hour, e.Minute, e.Second)
'
'    End Sub
'
'End Class

#End Region

#Region " Option Statements "

Option Strict On
Option Explicit On
Option Infer Off

#End Region

#Region " Imports "

Imports System.ComponentModel

#End Region

''' <summary>
''' Measure a time interval.
''' This can be used as a chronometer or countdown timer.
''' </summary>
Public NotInheritable Class TimeMeasurer

#Region " Objects "

   ''' <summary>
   ''' <see cref="Stopwatch"/> instance to retrieve the elapsed time.
   ''' </summary>
   Private TimeElapsed As Stopwatch

   ''' <summary>
   ''' <see cref="TimeSpan"/> instance to retrieve the remaining time.
   ''' </summary>
   Private TimeRemaining As TimeSpan

   ''' <summary>
   ''' <see cref="Timer"/> instance that updates the elapsed and remaining times and raises the events.
   ''' </summary>
   Private WithEvents MeasureTimer As Timer

   ''' <summary>
   ''' Indicates wheter the <see cref="TimeMeasurer"/> instance has finished to measure intervals.
   ''' </summary>
   Private IsFinished As Boolean

#End Region

#Region " Properties "

   ''' <summary>
   ''' Gets the current state of this <see cref="TimeMeasurer"/> instance.
   ''' </summary>
   ''' <value>The update interval.</value>
   Public ReadOnly Property State As TimeMeasurerState
       Get
           If Me.IsFinished Then
               Return TimeMeasurerState.Finished

           ElseIf (Me.TimeElapsed Is Nothing) OrElse Not (Me.TimeElapsed.IsRunning) Then
               Return TimeMeasurerState.Stopped

           Else
               Return TimeMeasurerState.Running

           End If
       End Get
   End Property

   ''' <summary>
   ''' Gets or sets the update interval.
   ''' </summary>
   ''' <value>The update interval.</value>
   Public Property UpdateInterval As Integer
       Get
           Return Me._UpdateInterval
       End Get
       Set(ByVal value As Integer)
           Me._UpdateInterval = value
           If Me.MeasureTimer IsNot Nothing Then
               Me.MeasureTimer.Interval = value
           End If
       End Set
   End Property
   ''' <summary>
   ''' The update interval
   ''' </summary>
   Private _UpdateInterval As Integer = 100I

#End Region

#Region " Enumerations "

   ''' <summary>
   ''' Specifies the current state of a <see cref="TimeMeasurer"/> instance.
   ''' </summary>
   <Description("Enum used as return value of 'State' property.")>
   Public Enum TimeMeasurerState As Integer

       ''' <summary>
       ''' The <see cref="TimeMeasurer"/> instance is running and measuring time intervals.
       ''' </summary>
       Running = 0I

       ''' <summary>
       ''' The <see cref="TimeMeasurer"/> instance is temporally stopped, waiting to resume.
       ''' </summary>
       Stopped = 1I

       ''' <summary>
       ''' The <see cref="TimeMeasurer"/> instance has finished to measure the time intervals.
       ''' </summary>
       Finished = 2I

   End Enum

#End Region

#Region " Events "

   ''' <summary>
   ''' Occurs when the elapsed time updates.
   ''' </summary>
   Public Event ElapsedTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)

   ''' <summary>
   ''' Occurs when the remaining time updates.
   ''' </summary>
   Public Event RemainingTimeUpdated(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)

   ''' <summary>
   ''' Occurs when the elapsed time finishes.
   ''' </summary>
   Public Event ElapsedTimeFinished(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)

   ''' <summary>
   ''' Occurs when the elapsed time finishes.
   ''' </summary>
   Public Event RemainingTimeFinished(ByVal sender As Object, ByVal e As TimeMeasureEventArgs)

   ''' <summary>
   ''' Contains the <see cref="TimeMeasureEventArgs"/> arguments.
   ''' </summary>
   Public Class TimeMeasureEventArgs : Inherits EventArgs

       ''' <summary>
       ''' Gets or sets the hour.
       ''' </summary>
       ''' <value>The hour.</value>
       Public Property Hour As Double

       ''' <summary>
       ''' Gets or sets the minute.
       ''' </summary>
       ''' <value>The minute.</value>
       Public Property Minute As Double

       ''' <summary>
       ''' Gets or sets the Second.
       ''' </summary>
       ''' <value>The Second.</value>
       Public Property Second As Double

       ''' <summary>
       ''' Gets or sets the Millisecond.
       ''' </summary>
       ''' <value>The Millisecond.</value>
       Public Property Millisecond As Double

   End Class

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Starts the time interval measurement from zero.
   ''' </summary>
   ''' <param name="Milliseconds">Indicates the time interval to measure, in milliseconds.</param>
   Public Sub Start(ByVal Milliseconds As Double)

       If Milliseconds > (TimeSpan.MaxValue.TotalMilliseconds - 1001.0R) Then
           Throw New ArgumentOutOfRangeException("Milliseconds",
                                                 String.Format("The value can't be greater than {0}",
                                                               CStr(TimeSpan.MaxValue.TotalMilliseconds - 1001.0R)))
       End If

       Me.TimeElapsed = New Stopwatch
       Me.TimeRemaining = TimeSpan.FromMilliseconds(Milliseconds)
       Me.MeasureTimer = New Timer With
          {
            .Tag = Milliseconds,
            .Interval = Me.UpdateInterval,
            .Enabled = True
          }

       Me.TimeElapsed.Start()
       Me.MeasureTimer.Start()

   End Sub

   ''' <summary>
   ''' Stops the time interval measurement.
   ''' </summary>
   Public Sub [Stop]()

       If (Me.MeasureTimer Is Nothing) OrElse Not (Me.TimeElapsed.IsRunning) Then
           Throw New Exception("TimeMeasurer is not running.")

       Else
           Me.MeasureTimer.Stop()
           Me.TimeElapsed.Stop()

       End If

   End Sub

   ''' <summary>
   ''' Resumes the time interval measurement.
   ''' </summary>
   Public Sub [Resume]()

       If (Me.MeasureTimer Is Nothing) OrElse (Me.TimeElapsed.IsRunning) Then
           Throw New Exception("TimeMeasurer is not stopped.")

       Else
           Me.MeasureTimer.Start()
           Me.TimeElapsed.Start()

       End If

   End Sub

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Stops Time intervals and resets the elapsed and remaining time to zero.
   ''' </summary>
   Private Sub Reset()

       Me.MeasureTimer.Stop()
       Me.TimeElapsed.Reset()

   End Sub

#End Region

#Region " Event Handlers "

   ''' <summary>
   ''' Handles the Tick event of the MeasureTimer control.
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
   Private Sub MeasureTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
   Handles MeasureTimer.Tick

       Dim TimeDifference As TimeSpan = (Me.TimeRemaining - Me.TimeElapsed.Elapsed)
       Dim ElapsedArgs As New TimeMeasureEventArgs
       Dim RemainingArgs As New TimeMeasureEventArgs

       If (TimeDifference.TotalMilliseconds <= 0.0R) _
       OrElse (Me.TimeElapsed.ElapsedMilliseconds > DirectCast(Me.MeasureTimer.Tag, Double)) Then

           Dim TotalTime As TimeSpan = TimeSpan.FromMilliseconds(DirectCast(Me.MeasureTimer.Tag, Double))

           With ElapsedArgs
               .Hour = TotalTime.Hours
               .Minute = TotalTime.Minutes
               .Second = TotalTime.Seconds
               .Millisecond = TotalTime.Milliseconds
           End With

           With RemainingArgs
               .Hour = 0.0R
               .Minute = 0.0R
               .Second = 0.0R
               .Millisecond = 0.0R
           End With

           Me.Reset()
           Me.IsFinished = True
           RaiseEvent ElapsedTimeFinished(Me.TimeElapsed, ElapsedArgs)
           RaiseEvent RemainingTimeFinished(TimeDifference, RemainingArgs)

       Else

           With ElapsedArgs
               .Hour = TimeElapsed.Elapsed.Hours
               .Minute = TimeElapsed.Elapsed.Minutes
               .Second = TimeElapsed.Elapsed.Seconds
               .Millisecond = TimeElapsed.Elapsed.Milliseconds
           End With

           With RemainingArgs
               .Hour = Math.Floor(TimeDifference.TotalHours) Mod TimeSpan.MaxValue.TotalMilliseconds
               .Minute = Math.Floor(TimeDifference.TotalMinutes) Mod 60.0R
               .Second = Math.Floor(TimeDifference.TotalSeconds) Mod 60.0R
               .Millisecond = Math.Floor(TimeDifference.TotalMilliseconds Mod 1000.0R)
           End With

           RaiseEvent ElapsedTimeUpdated(Me.TimeElapsed, ElapsedArgs)
           RaiseEvent RemainingTimeUpdated(TimeDifference, RemainingArgs)

       End If

   End Sub

#End Region

End Class








Eleкtro

#435
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:

[youtube=960,540]https://www.youtube.com/watch?v=6E3AEs66KaQ[/youtube]

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!








Eleкtro

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

Código (vbnet) [Seleccionar]
Public Class MyType

''' <summary>
''' Gets or sets the value.
''' </summary>
''' <value>The value.</value>
Public Property MyProperty As Integer
   Get
       Return Me._MyValue
   End Get
   Set(ByVal value As Integer)

       If value < Me._MyValueMin Then
           If Me._MyValueThrowRangeException Then
               Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage)
           End If
           Me._MyValue = Me._MyValueMin

       ElseIf value > Me._MyValueMax Then
           If Me._MyValueThrowRangeException Then
               Throw New ArgumentOutOfRangeException("MyValue", Me._MyValueExceptionMessage)
           End If
           Me._MyValue = Me._MyValueMax

       Else
           Me._MyValue = value

       End If

   End Set
End Property
Private _MyValue As Integer = 0I
Private _MyValueMin As Integer = 0I
Private _MyValueMax As Integer = 10I
Private _MyValueThrowRangeException As Boolean = True
   Private _MyValueExceptionMessage As String = String.Format("The valid range is beetwen {0} and {1}",
                                                          Me._MyValueMin, Me._MyValueMax)

End Class






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

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

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 09-23-2014
' ***********************************************************************
' <copyright file="DesktopVisibility.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

' DesktopVisibility.ShowDesktop()
' DesktopVisibility.HideDesktop()
' DesktopVisibility.ToggleDesktop()

#End Region

#Region " Imports "

Imports System.Runtime.InteropServices

#End Region

#Region " DesktopVisibility "

''' <summary>
''' Shows, hides, or toggles the desktop.
''' </summary>
Public NotInheritable Class DesktopVisibility

#Region " Objects "

   ''' <summary>
   ''' "Shell" CLASSID.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776890%28v=vs.85%29.aspx
   ''' </summary>
   Private Shared ReadOnly CLSIDShell As New Guid("13709620-C279-11CE-A49E-444553540000")

   ''' <summary>
   ''' Gets the objects in the Shell.
   ''' Methods are provided to control the Shell and to execute commands within the Shell.
   ''' There are also methods to obtain other Shell-related objects.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb774094%28v=vs.85%29.aspx
   ''' </summary>
   Private Shared ReadOnly Property Shell As Object
       Get
           If _Shell Is Nothing Then
               _Shell = Activator.CreateInstance(Type.GetTypeFromCLSID(CLSIDShell))
               Return _Shell
           Else
               Return _Shell
           End If
       End Get
   End Property
   Private Shared _Shell As Object = Nothing

#End Region

#Region " P/Invoke "

#Region " Methods "

   ''' <summary>
   ''' Retrieves a handle to the top-level window whose class name and window name match the specified strings.
   ''' This function does not search child windows.
   ''' This function does not perform a case-sensitive search.
   ''' To search child windows, beginning with a specified child window, use the FindWindowEx function.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="lpClassName">The class name.
   ''' If this parameter is NULL, it finds any window whose title matches the lpWindowName parameter.</param>
   ''' <param name="lpWindowName">The window name (the window's title).
   ''' If this parameter is NULL, all window names match.</param>
   ''' <returns>If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
   ''' If the function fails, the return value is NULL.</returns>
   <DllImport("user32.dll", SetLastError:=False)>
   Private Shared Function FindWindow(
           ByVal lpClassName As String,
           ByVal lpWindowName As String
   ) As IntPtr
   End Function

   ''' <summary>
   ''' Sends the specified message to a window or windows.
   ''' The SendMessage function calls the window procedure for the specified window
   ''' and does not return until the window procedure has processed the message.
   ''' </summary>
   ''' <param name="hWnd">A handle to the window whose window procedure will receive the message.</param>
   ''' <param name="Msg">The message to be sent.</param>
   ''' <param name="wParam">Additional message-specific information.</param>
   ''' <param name="lParam">Additional message-specific information.</param>
   ''' <returns>IntPtr.</returns>
   <DllImport("user32.dll", SetLastError:=False)>
   Private Shared Function SendMessage(
           ByVal hWnd As IntPtr,
           ByVal Msg As WindowsMessages,
           ByVal wParam As IntPtr,
           ByVal lParam As IntPtr
   ) As IntPtr
   End Function

#End Region

#Region " Enumerations "

   ''' <summary>
   ''' Specifies a System-Defined Message.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644927%28v=vs.85%29.aspx#system_defined
   ''' </summary>
   Public Enum WindowsMessages

       ''' <summary>
       ''' Message sent when the user selects a command item from a menu,
       ''' when a control sends a notification message to its parent window,
       ''' or when an accelerator keystroke is translated.
       ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms647591%28v=vs.85%29.aspx
       ''' </summary>
       WM_COMMAND = &H111UI

   End Enum

#End Region

#Region " Constants "

   ''' <summary>
   ''' Minimize all windows.
   ''' </summary>
   Const MIN_ALL As Integer = 419

   ''' <summary>
   ''' Undo the minimization of all minimized windows.
   ''' </summary>
   Const MIN_ALL_UNDO As Integer = 416

#End Region

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Shows the desktop.
   ''' </summary>
   Public Shared Sub ShowDesktop()

       SendMessage(FindWindow("Shell_TrayWnd", Nothing),
                   WindowsMessages.WM_COMMAND,
                   New IntPtr(MIN_ALL), IntPtr.Zero)

   End Sub

   ''' <summary>
   ''' Hides the desktop.
   ''' </summary>
   Public Shared Sub HideDesktop()

       SendMessage(FindWindow("Shell_TrayWnd", Nothing),
                   WindowsMessages.WM_COMMAND,
                   New IntPtr(MIN_ALL_UNDO), IntPtr.Zero)

   End Sub

   ''' <summary>
   ''' Shows or hides the desktop.
   ''' </summary>
   Public Shared Sub ToggleDesktop()

       Shell.ToggleDesktop() ' Doesns't works in Windows XP

   End Sub

#End Region

End Class

#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 (vbnet) [Seleccionar]

' ***********************************************************************
' Author           : Elektro
' Last Modified On : 10-01-2014
' ***********************************************************************
' <copyright file="SetWindowPosition.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Example Usage "

' SetWindowPosition.SetWindowPos("proceso.exe", SetWindowPosition.Corner.BottomRight)
' SetWindowPosition.SetWindowPos("proceso.exe", X:=100, Y:=100, Bounds:=SystemInformation.VirtualScreen)

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Runtime.InteropServices

#End Region

''' <summary>
''' Set the position of a window.
''' </summary>
Public Class SetWindowPosition

#Region " P/Invoke "

   ''' <summary>
   ''' Platform Invocation methods (P/Invoke), access unmanaged code.
   ''' This class does not suppress stack walks for unmanaged code permission.
   ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
   ''' This class is for methods that can be used anywhere because a stack walk will be performed.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
   ''' </summary>
   Protected NotInheritable Class NativeMethods

#Region " Methods "

       ''' <summary>
       ''' Changes the size, position, and Z order of a child, pop-up, or top-level window.
       ''' These windows are ordered according to their appearance on the screen.
       ''' The topmost window receives the highest rank and is the first window in the Z order.
       ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
       ''' </summary>
       ''' <param name="hWnd">
       ''' A handle to the window.
       ''' </param>
       ''' <param name="hWndInsertAfter">
       ''' A special handle to the window to precede the positioned window in the Z order.
       ''' This parameter must be a window handle or one of the <see cref="SpecialWindowHandles"/> values.
       ''' </param>
       ''' <param name="X">
       ''' The new position of the left side of the window, in client coordinates.
       ''' </param>
       ''' <param name="Y">
       ''' The new position of the top of the window, in client coordinates.
       ''' </param>
       ''' <param name="cx">
       ''' The new width of the window, in pixels.
       ''' </param>
       ''' <param name="cy">
       ''' The new height of the window, in pixels.
       ''' </param>
       ''' <param name="uFlags">
       ''' The window sizing and positioning flags.
       ''' </param>
       ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
       <DllImport("user32.dll", SetLastError:=True)>
       Friend Shared Function SetWindowPos(
              ByVal hWnd As IntPtr,
              ByVal hWndInsertAfter As SpecialWindowHandles,
              ByVal X As Integer,
              ByVal Y As Integer,
              ByVal cx As Integer,
              ByVal cy As Integer,
              ByVal uFlags As SetWindowPosFlags
       ) As Boolean
       End Function

       ''' <summary>
       ''' Retrieves the dimensions of the bounding rectangle of the specified window.
       ''' The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
       ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633519%28v=vs.85%29.aspx
       ''' </summary>
       ''' <param name="hWnd">A handle to the window.</param>
       ''' <param name="rc">
       ''' A pointer to a RECT structure that receives the screen coordinates of
       ''' the upper-left and lower-right corners of the window.
       ''' </param>
       ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
       <DllImport("user32.dll", SetLastError:=True)>
       Friend Shared Function GetWindowRect(
              ByVal hWnd As IntPtr,
              ByRef rc As Rectangle
       ) As Boolean
       End Function

#End Region

#Region " Enumerations "

       ''' <summary>
       ''' Specifies the window sizing and positioning flags.
       ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Enum used as 'uFlags' parameter of 'NativeMethods.SetWindowPos' function")>
       <Flags>
       Friend Enum SetWindowPosFlags As UInteger

           ''' <summary>
           ''' If the calling thread and the thread that owns the window are attached to different input queues,
           ''' the system posts the request to the thread that owns the window.
           ''' This prevents the calling thread from blocking its execution while other threads process the request.
           ''' </summary>
           ''' <remarks>SWP_ASYNCWINDOWPOS</remarks>
           SynchronousWindowPosition = &H4000UI

           ''' <summary>
           ''' Prevents generation of the WM_SYNCPAINT message.
           ''' </summary>
           ''' <remarks>SWP_DEFERERASE</remarks>
           DeferErase = &H2000UI

           ''' <summary>
           ''' Draws a frame (defined in the window's class description) around the window.
           ''' </summary>
           ''' <remarks>SWP_DRAWFRAME</remarks>
           DrawFrame = &H20UI

           ''' <summary>
           ''' Applies new frame styles set using the SetWindowLong function.
           ''' Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed.
           ''' If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
           ''' </summary>
           ''' <remarks>SWP_FRAMECHANGED</remarks>
           FrameChanged = &H20UI

           ''' <summary>
           ''' Hides the window.
           ''' </summary>
           ''' <remarks>SWP_HIDEWINDOW</remarks>
           HideWindow = &H80UI

           ''' <summary>
           ''' Does not activate the window.
           ''' If this flag is not set, the window is activated and moved to the top of
           ''' either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
           ''' </summary>
           ''' <remarks>SWP_NOACTIVATE</remarks>
           DoNotActivate = &H10UI

           ''' <summary>
           ''' Discards the entire contents of the client area. If this flag is not specified,
           ''' the valid contents of the client area are saved and copied back into the
           ''' client area after the window is sized or repositioned.
           ''' </summary>
           ''' <remarks>SWP_NOCOPYBITS</remarks>
           DoNotCopyBits = &H100UI

           ''' <summary>
           ''' Retains the current position (ignores X and Y parameters).
           ''' </summary>
           ''' <remarks>SWP_NOMOVE</remarks>
           IgnoreMove = &H2UI

           ''' <summary>
           ''' Does not change the owner window's position in the Z order.
           ''' </summary>
           ''' <remarks>SWP_NOOWNERZORDER</remarks>
           DoNotChangeOwnerZOrder = &H200UI

           ''' <summary>
           ''' Does not redraw changes.
           ''' If this flag is set, no repainting of any kind occurs.
           ''' This applies to  the client area, the nonclient area (including the title bar and scroll bars),
           ''' and any part of the parent window uncovered as a result of the window being moved.
           ''' When this flag is set, the application must explicitly invalidate or
           ''' redraw any parts of the window and parent window that need redrawing.
           ''' </summary>
           ''' <remarks>SWP_NOREDRAW</remarks>
           DoNotRedraw = &H8UI

           ''' <summary>
           ''' Same as the SWP_NOOWNERZORDER flag.
           ''' </summary>
           ''' <remarks>SWP_NOREPOSITION</remarks>
           DoNotReposition = &H200UI

           ''' <summary>
           ''' Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
           ''' </summary>
           ''' <remarks>SWP_NOSENDCHANGING</remarks>
           DoNotSendChangingEvent = &H400UI

           ''' <summary>
           ''' Retains the current size (ignores the cx and cy parameters).
           ''' </summary>
           ''' <remarks>SWP_NOSIZE</remarks>
           IgnoreResize = &H1UI

           ''' <summary>
           ''' Retains the current Z order (ignores the hWndInsertAfter parameter).
           ''' </summary>
           ''' <remarks>SWP_NOZORDER</remarks>
           IgnoreZOrder = &H4UI

           ''' <summary>
           ''' Displays the window.
           ''' </summary>
           ''' <remarks>SWP_SHOWWINDOW</remarks>
           ShowWindow = &H40UI

       End Enum

       ''' <summary>
       ''' Specifies a special handle to the window to precede the positioned window in the Z order.
       ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Enum used as 'hWndInsertAfter' parameter of 'NativeMethods.SetWindowPos' function")>
       Friend Enum SpecialWindowHandles As Integer

           ''' <summary>
           ''' Places the window at the top of the Z order.
           ''' </summary>
           Top = 0I

           ''' <summary>
           ''' Places the window at the bottom of the Z order.
           ''' If the hWnd parameter identifies a topmost window,
           ''' the window loses its topmost status and is placed at the bottom of all other windows.
           ''' </summary>
           Bottom = 1I

           ''' <summary>
           ''' Places the window above all non-topmost windows.
           ''' The window maintains its topmost position even when it is deactivated.
           ''' </summary>
           TopMost = -1I

           ''' <summary>
           ''' Places the window above all non-topmost windows (that is, behind all topmost windows).
           ''' This flag has no effect if the window is already a non-topmost window.
           ''' </summary>
           NoTopMost = -2I

       End Enum

#End Region

   End Class

#End Region

#Region " Enumerations "

   ''' <summary>
   ''' Specifies a screen corner.
   ''' </summary>
   <Description("Enum used as 'Corner' parameter of 'SetWindowPos' function")>
   Friend Enum Corner As Integer

       ''' <summary>
       ''' Top-Left screen corner.
       ''' </summary>
       TopLeft = 0I

       ''' <summary>
       ''' Top-Right screen corner.
       ''' </summary>
       TopRight = 1I

       ''' <summary>
       ''' Bottom-Left screen corner.
       ''' </summary>
       BottomLeft = 2I
       ''' <summary>
       ''' Bottom-Right screen corner.
       ''' </summary>0
       BottomRight = 3I

   End Enum

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Set the position of a window.
   ''' </summary>
   ''' <param name="ProcessName">The process name.</param>
   ''' <param name="Corner">The new window position, a screen corner.</param>
   ''' <param name="Bounds">
   ''' The screen <see cref="Rectangle"/> where the window is shown.
   ''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
   ''' </param>
   Friend Shared Sub SetWindowPos(ByVal ProcessName As String,
                                  ByVal Corner As Corner,
                                  Optional ByVal Bounds As Rectangle = Nothing)

       Dim Rect As Rectangle  ' The specified screen bounds
       Dim HWND As IntPtr     ' The process main window handle.
       Dim Width As Integer   ' The process window width.
       Dim Height As Integer  ' The process window height.
       Dim x As Integer
       Dim y As Integer

       If Bounds.IsEmpty Then
           Bounds = Screen.PrimaryScreen.WorkingArea
       End If

       ' Iterate the process instances.
       For Each p As Process In Process.GetProcessesByName(FixProcessName(ProcessName))

           Try
               ' Get the main window handle.
               HWND = p.MainWindowHandle

               ' Copy the process window position and size into the Rectangle.
               ' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
               NativeMethods.GetWindowRect(HWND, Rect)
               Width = (Rect.Width - Rect.Left)    ' Set the window width
               Height = (Rect.Height - Rect.Top) ' Set the window height

               Select Case Corner

                   Case SetWindowPosition.Corner.TopLeft
                       x = Bounds.Left
                       y = Bounds.Top

                   Case SetWindowPosition.Corner.TopRight
                       x = Bounds.Right - Width
                       y = Bounds.Top

                   Case SetWindowPosition.Corner.BottomLeft
                       x = Bounds.Left
                       y = Bounds.Bottom - Height

                   Case SetWindowPosition.Corner.BottomRight
                       x = Bounds.Right - Width
                       y = Bounds.Bottom - Height

               End Select

               ' Move the Main Window.
               NativeMethods.SetWindowPos(HWND, New IntPtr(NativeMethods.SpecialWindowHandles.NoTopMost),
                                          x, y, 0, 0,
                                          NativeMethods.SetWindowPosFlags.IgnoreResize)

           Catch ex As Exception
               Throw

           End Try

       Next

   End Sub

   ''' <summary>
   ''' Set the position of a window.
   ''' </summary>
   ''' <param name="ProcessName">The process name.</param>
   ''' <param name="X">The new X coordinate.</param>
   ''' <param name="Y">The new Y coordinate.</param>
   ''' <param name="Bounds">
   ''' The screen <see cref="Rectangle"/> where the window is shown.
   ''' If this parameter is empty, <see cref="Screen.PrimaryScreen"/> is used as default.
   ''' </param>
   Friend Shared Sub SetWindowPos(ByVal ProcessName As String,
                            ByVal X As Integer,
                            ByVal Y As Integer,
                            Optional ByVal Bounds As Rectangle = Nothing)

       Dim Rect As Rectangle  ' The specified screen bounds
       Dim HWND As IntPtr     ' The process main window handle.
       Dim Width As Integer   ' The process window width.
       Dim Height As Integer  ' The process window height.

       If Bounds.IsEmpty Then
           Bounds = Screen.PrimaryScreen.WorkingArea
       End If

       ' Iterate the process instances.
       For Each p As Process In Process.GetProcessesByName(FixProcessName(ProcessName))

           Try
               ' Get the main window handle.
               HWND = p.MainWindowHandle

               ' Copy the process window position and size into the Rectangle.
               ' NOTE: This is not a bad practice, but 'GetWindowRect' function should use a Windows API 'RECT' structure.
               NativeMethods.GetWindowRect(HWND, Rect)
               Width = (Rect.Width - Rect.Left)  ' Set the window width
               Height = (Rect.Height - Rect.Top) ' Set the window height

               ' Move the Main Window.
               NativeMethods.SetWindowPos(HWND, New IntPtr(NativeMethods.SpecialWindowHandles.NoTopMost),
                                          x, y, 0, 0,
                                          NativeMethods.SetWindowPosFlags.IgnoreResize)

           Catch ex As Exception
               Throw

           End Try

       Next

   End Sub

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Fixes the name of a process.
   ''' </summary>
   ''' <param name="name">The process name.</param>
   ''' <returns>System.String.</returns>
   Private Shared Function FixProcessName(ByVal name As String) As String

       If name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
           Return name.Remove(name.Length - ".exe".Length)
       Else
           Return name
       End If

   End Function

#End Region

End Class







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 (vbnet) [Seleccionar]
       ' Add or remove application from Windows Startup
       ' ( By Elektro )
       '
       ' Usage Examples :
       ' AddApplicationToWindowsStartup(User.CurrentUser, Application.ProductName, Application.ExecutablePath)
       ' RemoveApplicationFromWindowsStartup(User.CurrentUser, pplication.ProductName)

       ''' <summary>
       ''' Specifies a registry user session.
       ''' </summary>
       Public Enum User As Integer

           ''' <summary>
           ''' The current user session.
           ''' </summary>
           CurrentUser = 1I

           ''' <summary>
           ''' All user sessions.
           ''' </summary>
           AllUsers = 2I

       End Enum

       ''' <summary>
       ''' Adds an application to Windows Startup.
       ''' </summary>
       ''' <param name="User">Indicates the registry root key.</param>
       ''' <param name="Title">Indicates the registry value name.</param>
       ''' <param name="FilePath">Indicates the registry value data.</param>
       Friend Shared Sub AddApplicationToWindowsStartup(ByVal User As User,
                                                        ByVal Title As String,
                                                        ByVal FilePath As String)

           Try
               Select Case User

                   Case User.CurrentUser
                       My.Computer.Registry.CurrentUser.
                       OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
                       SetValue(Title, FilePath, Microsoft.Win32.RegistryValueKind.String)

                   Case User.AllUsers
                       My.Computer.Registry.LocalMachine.
                       OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
                       SetValue(Title, FilePath, Microsoft.Win32.RegistryValueKind.String)

                   Case Else
                       Exit Select

               End Select

           Catch ex As Exception
               Throw

           End Try

       End Sub

       ''' <summary>
       ''' Removes an application from Windows Startup.
       ''' </summary>
       ''' <param name="User">Indicates the registry root key.</param>
       ''' <param name="Title">Indicates the registry value name.</param>
       Friend Shared Sub RemoveApplicationFromWindowsStartup(ByVal User As User,
                                                             ByVal Title As String)
           Try

               Select Case User

                   Case User.CurrentUser
                       My.Computer.Registry.CurrentUser.
                       OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
                       DeleteValue(Title, throwOnMissingValue:=False)

                   Case User.AllUsers
                       My.Computer.Registry.LocalMachine.
                       OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", writable:=True).
                       DeleteValue(Title, throwOnMissingValue:=False)

                   Case Else
                       Exit Select

               End Select

           Catch ex As Exception
               Throw

           End Try

       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 (vbnet) [Seleccionar]
   ' Get x64 Process Path From x86
   ' ( By Elektro )
   '
   ' Instructions:
   ' 1. Add a reference to 'System.Management'
   '
   ' Usage Examples:
   ' Dim path As String = GetX64ProcessPathFromX86("conhost.exe")
   '
   ''' <summary>
   ''' Gets the process path of an x64 process from an x86 .NET application.
   ''' </summary>
   ''' <param name="ProcessName">Indicates the name of the process.</param>
   ''' <returns>The process path.</returns>
   Friend Shared Function GetX64ProcessPathFromX86(ByVal ProcessName As String) As String

       Dim wmiQuery As String = String.Format("SELECT ExecutablePath FROM Win32_Process Where Name = '{0}.exe'",
                                              If(ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase),
                                                 ProcessName.Remove(ProcessName.Length - ".exe".Length),
                                                 ProcessName))

       Using searcher As New ManagementObjectSearcher(queryString:=wmiQuery)

           Using results As ManagementObjectCollection = searcher.[Get]

               If results.Count <> 0I Then

                   Return DirectCast(DirectCast(results(0I), ManagementBaseObject).
                                     Properties("ExecutablePath").Value, String)

               Else
                   Return String.Empty

               End If

           End Using

       End Using

   End Function










Eleкtro

Modifica el estado de una ventana.

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 10-02-2014
' ***********************************************************************
' <copyright file="SetWindowState.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

'Dim HWND As IntPtr = Process.GetProcessesByName("devenv").First.MainWindowHandle
'
'SetWindowState.SetWindowState(HWND, SetWindowState.WindowState.Hide)
'SetWindowState.SetWindowState("devenv", SetWindowState.WindowState.Restore, Recursivity:=False)

#End Region

#Region " Imports "

Imports System.Runtime.InteropServices

#End Region

''' <summary>
''' Sets the state of a window.
''' </summary>
Public NotInheritable Class SetWindowState

#Region " P/Invoke "

    ''' <summary>
    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
    ''' This class does not suppress stack walks for unmanaged code permission.
    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
    ''' </summary>
    Protected NotInheritable Class NativeMethods

#Region " Methods "

        ''' <summary>
        ''' Retrieves a handle to the top-level window whose class name and window name match the specified strings.
        ''' This function does not search child windows.
        ''' This function does not perform a case-sensitive search.
        ''' To search child windows, beginning with a specified child window, use the FindWindowEx function.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="lpClassName">The class name.
        ''' If this parameter is NULL, it finds any window whose title matches the lpWindowName parameter.</param>
        ''' <param name="lpWindowName">The window name (the window's title).
        ''' If this parameter is NULL, all window names match.</param>
        ''' <returns>If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
        ''' If the function fails, the return value is NULL.</returns>
        <DllImport("user32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False)>
        Friend Shared Function FindWindow(
           ByVal lpClassName As String,
           ByVal lpWindowName As String
        ) As IntPtr
        End Function

        ''' <summary>
        ''' Retrieves a handle to a window whose class name and window name match the specified strings.
        ''' The function searches child windows, beginning with the one following the specified child window.
        ''' This function does not perform a case-sensitive search.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633500%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="hwndParent">
        ''' A handle to the parent window whose child windows are to be searched.
        ''' If hwndParent is NULL, the function uses the desktop window as the parent window.
        ''' The function searches among windows that are child windows of the desktop.
        ''' </param>
        ''' <param name="hwndChildAfter">
        ''' A handle to a child window.
        ''' The search begins with the next child window in the Z order.
        ''' The child window must be a direct child window of hwndParent, not just a descendant window.
        ''' If hwndChildAfter is NULL, the search begins with the first child window of hwndParent.
        ''' </param>
        ''' <param name="strClassName">
        ''' The window class name.
        ''' </param>
        ''' <param name="strWindowName">
        ''' The window name (the window's title).
        ''' If this parameter is NULL, all window names match.
        ''' </param>
        ''' <returns>
        ''' If the function succeeds, the return value is a handle to the window that has the specified class and window names.
        ''' If the function fails, the return value is NULL.
        ''' </returns>
        <DllImport("User32.dll", SetLastError:=False, CharSet:=CharSet.Auto, BestFitMapping:=False)>
        Friend Shared Function FindWindowEx(
           ByVal hwndParent As IntPtr,
           ByVal hwndChildAfter As IntPtr,
           ByVal strClassName As String,
           ByVal strWindowName As String
        ) As IntPtr
        End Function

        ''' <summary>
        ''' Retrieves the identifier of the thread that created the specified window
        ''' and, optionally, the identifier of the process that created the window.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633522%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="hWnd">A handle to the window.</param>
        ''' <param name="ProcessId">
        ''' A pointer to a variable that receives the process identifier.
        ''' If this parameter is not NULL, GetWindowThreadProcessId copies the identifier of the process to the variable;
        ''' otherwise, it does not.
        ''' </param>
        ''' <returns>The identifier of the thread that created the window.</returns>
        <DllImport("user32.dll")>
        Friend Shared Function GetWindowThreadProcessId(
            ByVal hWnd As IntPtr,
            ByRef ProcessId As Integer
        ) As Integer
        End Function

        ''' <summary>
        ''' Sets the specified window's show state.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="hwnd">A handle to the window.</param>
        ''' <param name="nCmdShow">Controls how the window is to be shown.</param>
        ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
        <DllImport("User32", SetLastError:=False)>
        Friend Shared Function ShowWindow(
           ByVal hwnd As IntPtr,
           ByVal nCmdShow As WindowState
        ) As Boolean
        End Function

#End Region

    End Class

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Controls how the window is to be shown.
    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
    ''' </summary>
    Friend Enum WindowState As Integer

        ''' <summary>
        ''' Hides the window and activates another window.
        ''' </summary>
        Hide = 0I

        ''' <summary>
        ''' Activates and displays a window.
        ''' If the window is minimized or maximized, the system restores it to its original size and position.
        ''' An application should specify this flag when displaying the window for the first time.
        ''' </summary>
        Normal = 1I

        ''' <summary>
        ''' Activates the window and displays it as a minimized window.
        ''' </summary>
        ShowMinimized = 2I

        ''' <summary>
        ''' Maximizes the specified window.
        ''' </summary>
        Maximize = 3I

        ''' <summary>
        ''' Activates the window and displays it as a maximized window.
        ''' </summary>     
        ShowMaximized = Maximize

        ''' <summary>
        ''' Displays a window in its most recent size and position.
        ''' This value is similar to <see cref="WindowState.Normal"/>, except the window is not actived.
        ''' </summary>
        ShowNoActivate = 4I

        ''' <summary>
        ''' Activates the window and displays it in its current size and position.
        ''' </summary>
        Show = 5I

        ''' <summary>
        ''' Minimizes the specified window and activates the next top-level window in the Z order.
        ''' </summary>
        Minimize = 6I

        ''' <summary>
        ''' Displays the window as a minimized window.
        ''' This value is similar to <see cref="WindowState.ShowMinimized"/>, except the window is not activated.
        ''' </summary>
        ShowMinNoActive = 7I

        ''' <summary>
        ''' Displays the window in its current size and position.
        ''' This value is similar to <see cref="WindowState.Show"/>, except the window is not activated.
        ''' </summary>
        ShowNA = 8I

        ''' <summary>
        ''' Activates and displays the window.
        ''' If the window is minimized or maximized, the system restores it to its original size and position.
        ''' An application should specify this flag when restoring a minimized window.
        ''' </summary>
        Restore = 9I

        ''' <summary>
        ''' Sets the show state based on the SW_* value specified in the STARTUPINFO structure
        ''' passed to the CreateProcess function by the program that started the application.
        ''' </summary>
        ShowDefault = 10I

        ''' <summary>
        ''' <b>Windows 2000/XP:</b>
        ''' Minimizes a window, even if the thread that owns the window is not responding.
        ''' This flag should only be used when minimizing windows from a different thread.
        ''' </summary>
        ForceMinimize = 11I

    End Enum

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Set the state of a window by an HWND.
    ''' </summary>
    ''' <param name="WindowHandle">A handle to the window.</param>
    ''' <param name="WindowState">The state of the window.</param>
    ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
    Friend Shared Function SetWindowState(ByVal WindowHandle As IntPtr,
                                          ByVal WindowState As WindowState) As Boolean

        Return NativeMethods.ShowWindow(WindowHandle, WindowState)

    End Function

    ''' <summary>
    ''' Set the state of a window by a process name.
    ''' </summary>
    ''' <param name="ProcessName">The name of the process.</param>
    ''' <param name="WindowState">The state of the window.</param>
    ''' <param name="Recursivity">If set to <c>false</c>, only the first process instance will be processed.</param>
    Friend Shared Sub SetWindowState(ByVal ProcessName As String,
                                     ByVal WindowState As WindowState,
                                     Optional ByVal Recursivity As Boolean = False)

        If ProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) Then
            ProcessName = ProcessName.Remove(ProcessName.Length - ".exe".Length)
        End If

        Dim pHandle As IntPtr = IntPtr.Zero
        Dim pID As Integer = 0I

        Dim Processes As Process() = Process.GetProcessesByName(ProcessName)

        ' If any process matching the name is found then...
        If Processes.Count = 0 Then
            Exit Sub
        End If

        For Each p As Process In Processes

            ' If Window is visible then...
            If p.MainWindowHandle <> IntPtr.Zero Then
                SetWindowState(p.MainWindowHandle, WindowState)

            Else ' Window is hidden

                ' Check all open windows (not only the process we are looking),
                ' begining from the child of the desktop, phandle = IntPtr.Zero initialy.
                While pID <> p.Id ' Check all windows.

                    ' Get child handle of window who's handle is "pHandle".
                    pHandle = NativeMethods.FindWindowEx(IntPtr.Zero, pHandle, Nothing, Nothing)

                    ' Get ProcessId from "pHandle".
                    NativeMethods.GetWindowThreadProcessId(pHandle, pID)

                    ' If the ProcessId matches the "pID" then...
                    If pID = p.Id Then

                        NativeMethods.ShowWindow(pHandle, WindowState)

                        If Not Recursivity Then
                            Exit For
                        End If

                    End If

                End While

            End If

        Next p

    End Sub

#End Region

End Class








Eleкtro

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

Código (vbnet) [Seleccionar]
   ' ( By Elektro )
   '
   ' Instructions:
   ' 1. Add a reference to 'Microsoft Shell Controls and Automation'
   '
   ' Usage Examples:
   ' Dim paths As List(Of String) = GetWindowsExplorerPaths()
   '
   ''' <summary>
   ''' Gets the full-path in the adressbar of each Windows Explorer instance.
   ''' MSDN Shell Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776890%28v=vs.85%29.aspx
   ''' </summary>
   ''' <returns>A list containing the paths.</returns>
   Friend Shared Function GetWindowsExplorerPaths() As List(Of String)

       Dim exShell As New Shell32.Shell
       Dim folder As Shell32.Folder
       Dim path As String
       Dim pathList As New List(Of String)

       For Each Window As SHDocVw.ShellBrowserWindow In DirectCast(exShell.Windows, SHDocVw.IShellWindows)

           folder = DirectCast(Window.Document, Shell32.ShellFolderView).Folder
           path = DirectCast(folder, Shell32.Folder2).Self.Path
           pathList.Add(path)

       Next Window

       Return pathList

   End Function


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








Eleкtro

#439
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 (vbnet) [Seleccionar]
Public Class PriorityList_TestForm

   ''' <summary>
   ''' Contains the process priority items.  
   ''' </summary>
   Private ReadOnly PriorityList As String() =
   {
       ProcessPriorityClass.Idle.ToString,
       ProcessPriorityClass.BelowNormal.ToString,
       ProcessPriorityClass.Normal.ToString,
       ProcessPriorityClass.AboveNormal.ToString,
       ProcessPriorityClass.High.ToString,
       ProcessPriorityClass.RealTime.ToString
   }

   ''' <summary>
   ''' Handles the Load event of the PriorityList_TestForm Form.
   ''' </summary>
   Private Shadows Sub Load() Handles MyBase.Load

       ' Add the priority items to list.
       Me.ComboBox1.Items.AddRange(Me.PriorityList)

   End Sub

   ''' <summary>
   ''' Handles the SelectedIndexChanged event of the ComboBox1 control.
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
   Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) _
   Handles ComboBox1.SelectedIndexChanged

       ' Change thecurrent  process priority.
       Process.GetCurrentProcess.PriorityClass =
           [Enum].Parse(GetType(ProcessPriorityClass),
                        DirectCast(sender, ComboBox).Text,
                        ignoreCase:=True)

   End Sub

End Class




Lo mismo, pero usando Telerik:

Código (vbnet) [Seleccionar]
Imports Telerik.WinControls.UI
Imports Telerik.WinControls.UI.Data

Public Class PriorityList_RadTestForm

   ''' <summary>
   ''' Contains the process priority items.  
   ''' </summary>
   Private ReadOnly PriorityList As New List(Of RadListDataItem) From
   {
       New RadListDataItem With {
           .Text = ProcessPriorityClass.Idle.ToString,
           .Value = ProcessPriorityClass.Idle
       },
       New RadListDataItem With {
           .Text = ProcessPriorityClass.BelowNormal.ToString,
           .Value = ProcessPriorityClass.BelowNormal
       },
       New RadListDataItem With {
           .Text = ProcessPriorityClass.Normal.ToString,
           .Value = ProcessPriorityClass.Normal
       },
       New RadListDataItem With {
           .Text = ProcessPriorityClass.AboveNormal.ToString,
           .Value = ProcessPriorityClass.AboveNormal
       },
       New RadListDataItem With {
           .Text = ProcessPriorityClass.High.ToString,
           .Value = ProcessPriorityClass.High
       },
       New RadListDataItem With {
           .Text = ProcessPriorityClass.RealTime.ToString,
           .Value = ProcessPriorityClass.RealTime
       }
   }

   ''' <summary>
   ''' Handles the Initialized event of the RadDropDownList1 control.
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
   Private Sub RadDropDownList1_Initialized(ByVal sender As Object, ByVal e As EventArgs) _
   Handles RadDropDownList1.Initialized

       ' Add the priority items to list.
       DirectCast(sender, RadDropDownList).Items.AddRange(PriorityList)

   End Sub

   ''' <summary>
   ''' Handles the SelectedIndexChanged event of the RadDropDownList1 control.
   ''' </summary>
   ''' <param name="sender">The source of the event.</param>
   ''' <param name="e">The <see cref="Telerik.WinControls.UI.Data.PositionChangedEventArgs"/> instance containing the event data.</param>
   Private Sub RadDropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As PositionChangedEventArgs) _
   Handles RadDropDownList1.SelectedIndexChanged

       ' Change thecurrent  process priority.
       Process.GetCurrentProcess.PriorityClass =
           DirectCast(DirectCast(sender, RadDropDownList).SelectedItem.Value, ProcessPriorityClass)

   End Sub

End Class