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


Tema destacado: Como proteger una cartera - billetera de Bitcoin


  Mostrar Mensajes
Páginas: 1 ... 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 [638] 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 ... 1254
6371  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 30 Noviembre 2014, 01:44 am
Ejemplo de cómo utilizar la librería SharpShell para crear una shell-extensión, un menú contextual para nuestra aplicación: https://sharpshell.codeplex.com



La imagen de arriba no hace referencia al siguiente ejemplo, mi menú tiene la siguiente estructura:

Código:
· Título
         (Sub-menu)
         · Run
         · Open Files...

Código
  1. #Region " Option Statements "
  2.  
  3. Option Strict On
  4. Option Explicit On
  5. Option Infer Off
  6.  
  7. #End Region
  8.  
  9. #Region " Imports "
  10.  
  11. Imports SharpShell.Attributes
  12. Imports SharpShell.SharpContextMenu
  13. Imports System.IO
  14. Imports System.Runtime.InteropServices
  15. Imports System.Text
  16. Imports System.Windows.Forms
  17. Imports System.ComponentModel
  18.  
  19. #End Region
  20.  
  21. #Region " MyAppContextMenu "
  22.  
  23. ''' <summary>
  24. ''' The Application Context Menu Extension.
  25. ''' </summary>
  26. <ComVisible(True)>
  27. <COMServerAssociation(AssociationType.ClassOfExtension, ".ext")>
  28. Public Class MyAppContextMenu : Inherits SharpContextMenu
  29.  
  30. #Region " Objects "
  31.  
  32.    ''' <summary>
  33.    ''' Contains the application information.
  34.    ''' </summary>
  35.    Private ReadOnly application As New AppInfo With
  36.            {
  37.                .Title = "Menu Title",
  38.                .Filename = "Application Filename",
  39.                .Directory = My.Application.Info.DirectoryPath
  40.            }
  41.  
  42. #End Region
  43.  
  44. #Region " Types "
  45.  
  46.    ''' <summary>
  47.    ''' Contains information about an application.
  48.    ''' This class cannot be inherited.
  49.    ''' </summary>
  50.    Protected NotInheritable Class AppInfo
  51.  
  52.        ''' <summary>
  53.        ''' Gets or sets the application title.
  54.        ''' </summary>
  55.        ''' <value>The application title.</value>
  56.        Protected Friend Property Title As String
  57.  
  58.        ''' <summary>
  59.        ''' Gets or sets the application filename.
  60.        ''' </summary>
  61.        ''' <value>The application filename.</value>
  62.        Protected Friend Property Filename As String
  63.  
  64.        ''' <summary>
  65.        ''' Gets or sets the application working directory.
  66.        ''' </summary>
  67.        ''' <value>The application working directory.</value>
  68.        Protected Friend Property Directory As String
  69.  
  70.        ''' <summary>
  71.        ''' Gets the full qualified application path.
  72.        ''' </summary>
  73.        ''' <value>The full qualified application path.</value>
  74.        Protected Friend ReadOnly Property FullPath As String
  75.            Get
  76.                Return Path.Combine(Me.Directory, Me.Filename, ".exe")
  77.            End Get
  78.        End Property
  79.  
  80.    End Class
  81.  
  82. #End Region
  83.  
  84. #Region " SharpShell Methods "
  85.  
  86.    ''' <summary>
  87.    ''' Determines whether this instance can a shell context show menu, given the specified selected file list.
  88.    ''' </summary>
  89.    ''' <returns>
  90.    ''' <c>true</c> if this instance should show a shell context menu for the specified file list; otherwise, <c>false</c>.
  91.    ''' </returns>
  92.    Protected Overrides Function CanShowMenu() As Boolean
  93.  
  94.        Return True
  95.  
  96.    End Function
  97.  
  98.    ''' <summary>
  99.    ''' Creates the context menu.
  100.    ''' </summary>
  101.    ''' <returns>The context menu for the shell context menu.</returns>
  102.    Protected Overrides Function CreateMenu() As ContextMenuStrip
  103.  
  104.        ' Create the menu strip.
  105.        Dim menu As New ContextMenuStrip()
  106.  
  107.        ' Create the main item, this is used to show our application title.
  108.        Dim itemTitle As New ToolStripMenuItem() With
  109.            {
  110.                .Text = Me.application.Title,
  111.                .Image = My.Resources.TitleIcon
  112.            }
  113.  
  114.        ' Create a 'Run' item.
  115.        Dim itemRun As New ToolStripMenuItem() With
  116.            {
  117.                .Text = "Run",
  118.                .Image = My.Resources.RunIcon
  119.            }
  120.  
  121.        ' Create a 'Open file' item.
  122.        Dim itemOpenFile As New ToolStripMenuItem() With
  123.            {
  124.                .Text = "Open file...",
  125.                .Image = My.Resources.OpenFileIcon
  126.            }
  127.  
  128.        ' Create a 'Open files' item.
  129.        Dim itemOpenFiles As New ToolStripMenuItem() With
  130.            {
  131.                .Text = "Open files...",
  132.                .Image = My.Resources.OpenFileIcon
  133.            }
  134.  
  135.        ' Add the main item into the context menu.
  136.        menu.Items.Add(itemTitle)
  137.  
  138.        ' Add the 'Run' sub-item into the 'itemTitle' item.
  139.        itemTitle.DropDownItems.Add(itemRun)
  140.  
  141.        ' Add the 'Open file' or 'Open files' sub-item into the 'itemTitle' item.
  142.        ' Depending on the amount of selected files.
  143.        itemTitle.DropDownItems.Add(If(Me.SelectedItemPaths.Count = 1, itemOpenFile, itemOpenFiles))
  144.  
  145.        ' Suscribe to events.
  146.        AddHandler itemRun.Click, AddressOf ItemRun_Click
  147.        AddHandler itemOpenFile.Click, AddressOf ItemOpenFile_Click
  148.        AddHandler itemOpenFiles.Click, AddressOf ItemOpenFiles_Click
  149.  
  150.        ' Return the menu.
  151.        Return menu
  152.  
  153.    End Function
  154.  
  155. #End Region
  156.  
  157. #Region " Application Methods "
  158.  
  159.    ''' <summary>
  160.    ''' Runs the specified application.
  161.    ''' </summary>
  162.    ''' <param name="fileName">The name of an application file to run in the process.</param>
  163.    ''' <param name="arguments">Command-line arguments to pass when starting the process.</param>
  164.    Private Sub RunApp(ByVal fileName As String,
  165.                       Optional ByVal arguments As String = "")
  166.  
  167.        Try
  168.            Process.Start(fileName, arguments)
  169.  
  170.        Catch ex As FileNotFoundException
  171.            ' Do something.
  172.  
  173.        Catch ex As InvalidOperationException
  174.            ' Do something.
  175.  
  176.        Catch ex As Win32Exception
  177.            ' Dim errorCode As Integer = Marshal.GetLastWin32Error()
  178.            ' Do something.
  179.  
  180.        Catch ex As Exception
  181.            ' Do something.
  182.  
  183.        End Try
  184.  
  185.    End Sub
  186.  
  187.    ''' <summary>
  188.    ''' Opens the given file in the specified application.
  189.    ''' </summary>
  190.    ''' <param name="appPath">The application filepath to run.</param>
  191.    ''' <param name="filepath">The filepath to send to the application arguments.</param>
  192.    ''' <param name="stringFormat">The string format used to format the filepath.</param>
  193.    Private Sub OpenFile(ByVal appPath As String,
  194.                         ByVal filepath As String,
  195.                         Optional ByVal stringFormat As String = """{0}""")
  196.  
  197.        Me.RunApp(appPath, String.Format(stringFormat, filepath))
  198.  
  199.    End Sub
  200.  
  201.    ''' <summary>
  202.    ''' Opens the given files in the specified application.
  203.    ''' </summary>
  204.    ''' <param name="appPath">The application filepath to run.</param>
  205.    ''' <param name="filepaths">The filepaths to send to the application arguments.</param>
  206.    ''' <param name="stringFormat">The string format used to join the filepaths.</param>
  207.    Private Sub OpenFiles(ByVal appPath As String,
  208.                          ByVal filepaths As IEnumerable(Of String),
  209.                          Optional ByVal stringFormat As String = """{0}"" ")
  210.  
  211.        Me.RunApp(fileName:=appPath,
  212.                  arguments:=Me.JoinFilePaths(filepaths, stringFormat))
  213.  
  214.    End Sub
  215.  
  216.    ''' <summary>
  217.    ''' Joins the selected filepaths in a single line, filepaths are closed with double-quotes and separated by a space.
  218.    ''' eg: "File1" "File2" "File3"
  219.    ''' </summary>
  220.    ''' <param name="filepaths">The filepaths to join.</param>
  221.    ''' <param name="joinFormat">The string format used to join the filepaths.</param>
  222.    ''' <returns>The joined and formatted filepaths.</returns>
  223.    Private Function JoinFilePaths(ByVal filepaths As IEnumerable(Of String),
  224.                                   ByVal joinFormat As String) As String
  225.  
  226.        Dim sb As New StringBuilder()
  227.  
  228.        For Each filePath As String In filepaths
  229.            sb.Append(String.Format(joinFormat, filePath))
  230.        Next filePath
  231.  
  232.        Return sb.ToString
  233.  
  234.    End Function
  235.  
  236. #End Region
  237.  
  238. #Region " Event Handlers "
  239.  
  240.    ''' <summary>
  241.    ''' Handles the Click event of the ItemRun menu item.
  242.    ''' </summary>
  243.    ''' <param name="sender">The source of the event.</param>
  244.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  245.    Private Sub ItemRun_Click(ByVal sender As Object, ByVal e As EventArgs)
  246.  
  247.        Me.RunApp(fileName:=Me.application.FullPath)
  248.  
  249.    End Sub
  250.  
  251.    ''' <summary>
  252.    ''' Handles the Click event of the ItemOpenFile menu item.
  253.    ''' </summary>
  254.    ''' <param name="sender">The source of the event.</param>
  255.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  256.    Private Sub ItemOpenFile_Click(ByVal sender As Object, ByVal e As EventArgs)
  257.  
  258.        Me.OpenFile(appPath:=Me.application.FullPath,
  259.                    filepath:=Me.SelectedItemPaths.First)
  260.  
  261.    End Sub
  262.  
  263.    ''' <summary>
  264.    ''' Handles the Click event of the ItemOpenFiles menu item.
  265.    ''' </summary>
  266.    ''' <param name="sender">The source of the event.</param>
  267.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  268.    Private Sub ItemOpenFiles_Click(ByVal sender As Object, ByVal e As EventArgs)
  269.  
  270.        Me.OpenFiles(appPath:=Me.application.FullPath,
  271.                     filepaths:=Me.SelectedItemPaths)
  272.  
  273.    End Sub
  274.  
  275. #End Region
  276.  
  277. End Class
  278.  
  279. #End Region
  280.  

6372  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 30 Noviembre 2014, 01:42 am
Una actualización de este ayudante para "renombrar" o capitalizar un String, dándole el formato deseado.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 29-November-2014
  4. ' ***********************************************************************
  5. ' <copyright file="StringRenamer.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Option Statements "
  11.  
  12. Option Explicit On
  13. Option Strict On
  14. Option Infer Off
  15.  
  16. #End Region
  17.  
  18. #Region " Usage Examples "
  19.  
  20. ' MsgBox(StringRenamer.Rename("Hello World!", StringRenamer.FormatCase.Upper))
  21. ' MsgBox(StringRenamer.Rename("Hello World!", StringRenamer.FormatCase.Upper, "\s+", "-", System.Text.RegularExpressions.RegexOptions.None))
  22.  
  23. #End Region
  24.  
  25. #Region " Imports "
  26.  
  27. Imports System.Text
  28. Imports System.Text.RegularExpressions
  29. Imports System.Globalization
  30.  
  31. #End Region
  32.  
  33. #Region " String Renamer "
  34.  
  35. ''' <summary>
  36. ''' Renames a string.
  37. ''' </summary>
  38. Public NotInheritable Class StringRenamer
  39.  
  40. #Region " Enumerations "
  41.  
  42.    ''' <summary>
  43.    ''' Specifies a string format case.
  44.    ''' </summary>
  45.    Public Enum FormatCase As Integer
  46.  
  47.        ''' <summary>
  48.        ''' LowerCase
  49.        '''
  50.        ''' [Example]
  51.        ''' Input : ABCDEF
  52.        ''' Output: abcdef
  53.        ''' </summary>
  54.        Lower = &H0
  55.  
  56.        ''' <summary>
  57.        ''' UpperCase.
  58.        '''
  59.        ''' [Example]
  60.        ''' Input : abcdef
  61.        ''' Output: ABCDEF
  62.        ''' </summary>
  63.        Upper = &H1
  64.  
  65.        ''' <summary>
  66.        ''' TitleCase.
  67.        '''
  68.        ''' [Example]
  69.        ''' Input : abcdef
  70.        ''' Output: Abcdef
  71.        ''' </summary>
  72.        Title = &H2
  73.  
  74.        ''' <summary>
  75.        ''' WordCase.
  76.        '''
  77.        ''' [Example]
  78.        ''' Input : abc def
  79.        ''' Output: Abc Def
  80.        ''' </summary>
  81.        Word = &H3
  82.  
  83.        ''' <summary>
  84.        ''' CamelCase (With first letter to LowerCase).
  85.        '''
  86.        ''' [Example]
  87.        ''' Input : ABC DEF
  88.        ''' Output: abcDef
  89.        ''' </summary>
  90.        CamelLower = &H4
  91.  
  92.        ''' <summary>
  93.        ''' CamelCase (With first letter to UpperCase).
  94.        '''
  95.        ''' [Example]
  96.        ''' Input : ABC DEF
  97.        ''' Output: AbcDef
  98.        ''' </summary>
  99.        CamelUpper = &H5
  100.  
  101.        ''' <summary>
  102.        ''' MixedCase (With first letter to LowerCase).
  103.        '''
  104.        ''' [Example]
  105.        ''' Input : ab cd ef
  106.        ''' Output: aB Cd eF
  107.        ''' </summary>
  108.        MixedTitleLower = &H6
  109.  
  110.        ''' <summary>
  111.        ''' MixedCase (With first letter to UpperCase).
  112.        '''
  113.        ''' [Example]
  114.        ''' Input : ab cd ef
  115.        ''' Output: Ab cD Ef
  116.        ''' </summary>
  117.        MixedTitleUpper = &H7
  118.  
  119.        ''' <summary>
  120.        ''' MixedCase (With first letter of each word to LowerCase).
  121.        '''
  122.        ''' [Example]
  123.        ''' Input : ab cd ef
  124.        ''' Output: aB cD eF
  125.        ''' </summary>
  126.        MixedWordLower = &H8
  127.  
  128.        ''' <summary>
  129.        ''' MixedCase (With first letter of each word to UpperCase).
  130.        '''
  131.        ''' [Example]
  132.        ''' Input : ab cd ef
  133.        ''' Output: Ab Cd Ef
  134.        ''' </summary>
  135.        MixedWordUpper = &H9
  136.  
  137.        ''' <summary>
  138.        ''' ToggleCase.
  139.        '''
  140.        ''' [Example]
  141.        ''' Input : abc def ghi
  142.        ''' Output: aBC dEF gHI
  143.        ''' </summary>
  144.        Toggle = &H10
  145.  
  146.        ''' <summary>
  147.        ''' Duplicates the characters.
  148.        '''
  149.        ''' [Example]
  150.        ''' Input : Hello World!
  151.        ''' Output: HHeelllloo  WWoorrlldd!!
  152.        ''' </summary>
  153.        Duplicated = &H11
  154.  
  155.        ''' <summary>
  156.        ''' Inverts the characters.
  157.        '''
  158.        ''' [Example]
  159.        ''' Input : Hello World!
  160.        ''' Output: hELLO wORLD!
  161.        ''' </summary>
  162.        Inverted = &H12
  163.  
  164.    End Enum
  165.  
  166. #End Region
  167.  
  168. #Region " Publix Methods "
  169.  
  170. #End Region
  171.  
  172.    ''' <summary>
  173.    ''' Renames a string to the specified StringCase.
  174.    ''' </summary>
  175.    ''' <param name="str">The string to rename.</param>
  176.    ''' <param name="fCase">The format case.</param>
  177.    ''' <returns>The renamed string.</returns>
  178.    Public Shared Function Rename(ByVal str As String,
  179.                                  ByVal fCase As FormatCase) As String
  180.  
  181.        Select Case fCase
  182.  
  183.            Case FormatCase.Lower
  184.                Return str.ToLower
  185.  
  186.            Case FormatCase.Upper
  187.                Return str.ToUpper
  188.  
  189.            Case FormatCase.Title
  190.                Return Char.ToUpper(str.First) & str.Substring(1).ToLower
  191.  
  192.            Case FormatCase.Word
  193.                Return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str.ToLower)
  194.  
  195.            Case FormatCase.CamelLower
  196.                Return Char.ToLower(str.First) &
  197.                       CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str.ToLower).
  198.                       Replace(" "c, String.Empty).
  199.                       Substring(1)
  200.  
  201.            Case FormatCase.CamelUpper
  202.                Return Char.ToUpper(str.First) &
  203.                       CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str.ToLower).
  204.                       Replace(" "c, String.Empty).
  205.                       Substring(1)
  206.  
  207.            Case FormatCase.MixedTitleLower
  208.                Dim sb As New StringBuilder
  209.                For i As Integer = 0 To (str.Length - 1) Step 2
  210.                    If Not (i + 1) >= str.Length Then
  211.                        sb.Append(Char.ToLower(str(i)) & Char.ToUpper(str(i + 1)))
  212.                    Else
  213.                        sb.Append(Char.ToLower(str(i)))
  214.                    End If
  215.                Next i
  216.                Return sb.ToString
  217.  
  218.            Case FormatCase.MixedTitleUpper
  219.                Dim sb As New StringBuilder
  220.                For i As Integer = 0 To (str.Length - 1) Step 2
  221.                    If Not (i + 1) >= str.Length Then
  222.                        sb.Append(Char.ToUpper(str(i)) & Char.ToLower(str(i + 1)))
  223.                    Else
  224.                        sb.Append(Char.ToUpper(str(i)))
  225.                    End If
  226.                Next i
  227.                Return sb.ToString
  228.  
  229.            Case FormatCase.MixedWordLower
  230.                Dim sb As New StringBuilder
  231.                For Each token As String In str.Split
  232.                    sb.Append(StringRenamer.Rename(token, FormatCase.MixedTitleLower) & " ")
  233.                Next token
  234.                Return sb.ToString
  235.  
  236.            Case FormatCase.MixedWordUpper
  237.                Dim sb As New StringBuilder
  238.                For Each token As String In str.Split
  239.                    sb.Append(StringRenamer.Rename(token, FormatCase.MixedTitleUpper) & " ")
  240.                Next token
  241.                Return sb.ToString
  242.  
  243.            Case FormatCase.Toggle
  244.                Dim sb As New StringBuilder
  245.                For Each token As String In str.Split
  246.                    sb.Append(Char.ToLower(token.First) & token.Substring(1).ToUpper & " ")
  247.                Next token
  248.                Return sb.ToString
  249.  
  250.            Case FormatCase.Duplicated
  251.                Dim sb As New StringBuilder
  252.                For Each c As Char In str
  253.                    sb.Append(New String(c, 2))
  254.                Next c
  255.                Return sb.ToString
  256.  
  257.            Case FormatCase.Inverted
  258.                Dim sb As New StringBuilder
  259.                For Each c As Char In str
  260.                    sb.Append(If(Char.IsLower(c),
  261.                                 Char.ToUpper(c),
  262.                                 Char.ToLower(c)))
  263.                Next c
  264.                Return sb.ToString
  265.  
  266.            Case Else
  267.                Return str
  268.  
  269.        End Select
  270.  
  271.    End Function
  272.  
  273.    ''' <summary>
  274.    ''' Rename a string to the specified StringCase,
  275.    ''' Also finds and replaces text after the string is renamed.
  276.    ''' </summary>
  277.    ''' <param name="str">The string to rename.</param>
  278.    ''' <param name="fCase">The format case.</param>
  279.    ''' <param name="FindWhat">The RegEx pattern to match.</param>
  280.    ''' <param name="ReplaceWith">The replacement string.</param>
  281.    ''' <param name="regexOptions">The RegEx options.</param>
  282.    ''' <returns>The renamed string.</returns>
  283.    Public Shared Function Rename(ByVal str As String,
  284.                                  ByVal fCase As FormatCase,
  285.                                  ByVal findWhat As String,
  286.                                  ByVal replaceWith As String,
  287.                                  ByVal regexOptions As RegexOptions) As String
  288.  
  289.        Return Regex.Replace(StringRenamer.Rename(str, fCase),
  290.                             findWhat,
  291.                             replaceWith,
  292.                             regexOptions)
  293.  
  294.    End Function
  295.  
  296. End Class
  297.  
  298. #End Region



Ejemplo de como filtrar las extensiones mostradas en un FolderView control, de la librería shell mega pack: http://www.ssware.com/fldrview.htm



Código
  1.        ''' <summary>
  2.        ''' Handles the AfterExpand event of the FolderView1 control.
  3.        ''' </summary>
  4.        ''' <param name="sender">The source of the event.</param>
  5.        ''' <param name="e">The <see cref="FolderViewEventArgs"/> instance containing the event data.</param>
  6.        Private Sub FolderView1_AfterExpand(ByVal sender As Object, ByVal e As FolderViewEventArgs) _
  7.        Handles FolderView1.AfterExpand
  8.  
  9.            ' This event occurs when node is expanded.
  10.  
  11.            If e.Node.HasExpandedOnce Then
  12.                Exit Sub
  13.            End If
  14.  
  15.            Me.FilterNodeFiles(folderView:=DirectCast(sender, FolderView),
  16.                               allowedExtensions:=".mp3".ToLower.Split)
  17.  
  18.        End Sub
  19.  
  20.        ''' <summary>
  21.        ''' Handles the BeforeNodeSort event of the FolderView1 control.
  22.        ''' </summary>
  23.        ''' <param name="sender">The source of the event.</param>
  24.        ''' <param name="e">The <see cref="BeforeNodeSortEventArgs"/> instance containing the event data.</param>
  25.        Private Sub FolderView1_BeforeNodeSort(sender As Object, e As BeforeNodeSortEventArgs) _
  26.        Handles FolderView1.BeforeNodeSort
  27.  
  28.            ' This event occurs when a file is created/moved/pasted inside a node.
  29.  
  30.            Me.FilterNodeFiles(folderView:=DirectCast(sender, FolderView),
  31.                               allowedExtensions:=".mp3".ToLower.Split)
  32.  
  33.        End Sub
  34.  
  35.        ''' <summary>
  36.        ''' Filters the files that can be shown in the TreeNodes of a <see cref="FolderView"/>.
  37.        ''' </summary>
  38.        ''' <param name="folderView">The <see cref="FolderView"/>.</param>
  39.        ''' <param name="allowedExtensions">The allowed file extensions.</param>
  40.        Private Sub FilterNodeFiles(ByVal folderView As FolderView, ByVal allowedExtensions() As String)
  41.  
  42.            For Each node As FOVTreeNode In folderView.Nodes.Cast(Of FOVTreeNode).Reverse
  43.  
  44.                If Not (node.IsFolder) _
  45.                AndAlso Not (allowedExtensions.Contains(IO.Path.GetExtension(node.Text).ToLower)) Then
  46.  
  47.                    node.Delete()
  48.  
  49.                End If
  50.  
  51.            Next node
  52.  
  53.        End Sub
  54.  



Una actualización de este ayudante de la librería TagLibSharp, para la edición de metadats de archivos de audio, ese wrapper está orientado al manejo de archivos MP3 solamente.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 29-Novembder-2014
  4. ' ***********************************************************************
  5. ' <copyright file="TagLibSharp Helper.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Dim tagger As New TagLibSharpHelper
  13. 'tagger.LoadFile("C:\Users\Administrador\Desktop\1.mp3")
  14.  
  15. 'Dim sb As New System.Text.StringBuilder
  16. 'With sb
  17. '    .AppendLine(String.Format("Is Corrupt?: {0}", tagger.IsCorrupt))
  18. '    .AppendLine(String.Format("Is Writeable?: {0}", tagger.IsWriteable))
  19. '    .AppendLine()
  20. '    .AppendLine(String.Format("Tags: {0}", tagger.GetTags))
  21. '    .AppendLine()
  22. '    .AppendLine(String.Format("Title: {0}", tagger.GetTitle))
  23. '    .AppendLine(String.Format("Artist: {0}", tagger.GetArtist))
  24. '    .AppendLine(String.Format("Album: {0}", tagger.GetAlbum))
  25. '    .AppendLine(String.Format("Genre: {0}", tagger.GetGenre))
  26. '    .AppendLine(String.Format("Year: {0}", tagger.GetYear))
  27. 'End With
  28. 'MessageBox.Show(sb.ToString)
  29.  
  30. 'tagger.RemoveTag(TagLib.TagTypes.Id3v1 Or TagLib.TagTypes.Id3v2) ' Removes ID3v1 + ID3v2 Tags
  31.  
  32. 'tagger.SetTag(Sub(x As TagLib.File) x.Tag.Title = "Title Test")
  33.  
  34. 'tagger.SetTags({Sub(x As TagLib.File) x.Tag.Title = "Title Test",
  35. '                Sub(x As TagLib.File) x.Tag.Performers = {"My Artist"}})
  36.  
  37. #End Region
  38.  
  39. #Region " Option Statements "
  40.  
  41. Option Strict On
  42. Option Explicit On
  43. Option Infer Off
  44.  
  45. #End Region
  46.  
  47. #Region " Imports "
  48.  
  49. Imports TagLib
  50.  
  51. #End Region
  52.  
  53. #Region " TagLibSharp Helper "
  54.  
  55. Public NotInheritable Class TagLibSharpHelper
  56.  
  57. #Region " Properties "
  58.  
  59.    ''' <summary>
  60.    ''' Gets or sets the <see cref="TagLib.File"/> object.
  61.    ''' </summary>
  62.    ''' <value>The <see cref="TagLib.File"/> object.</value>
  63.    Private Property TagFile As TagLib.File
  64.  
  65.    Public ReadOnly Property CurrentFile As String
  66.        Get
  67.            Return Me.TagFile.Name
  68.        End Get
  69.    End Property
  70.  
  71. #End Region
  72.  
  73. #Region " Constructors "
  74.  
  75.    ''' <summary>
  76.    ''' Initializes a new instance of the <see cref="TagLibSharpHelper"/> class.
  77.    ''' </summary>
  78.    Public Sub New()
  79.    End Sub
  80.  
  81.    ''' <summary>
  82.    ''' Initializes a new instance of the <see cref="TagLibSharpHelper" /> class.
  83.    ''' </summary>
  84.    ''' <param name="file">The file to load.</param>
  85.    Public Sub New(ByVal file As String)
  86.        Me.LoadFile(file)
  87.    End Sub
  88.  
  89. #End Region
  90.  
  91. #Region " Public Methods "
  92.  
  93.    ''' <summary>
  94.    ''' Instances a file.
  95.    ''' </summary>
  96.    ''' <param name="file">The file to load.</param>
  97.    Public Sub LoadFile(ByVal file As String)
  98.  
  99.        Try
  100.            Me.TagFile = TagLib.File.Create(file)
  101.  
  102.        Catch ex As CorruptFileException
  103.            Throw
  104.  
  105.        Catch ex As UnsupportedFormatException
  106.            Throw
  107.  
  108.        Catch ex As Exception
  109.            Throw
  110.  
  111.        End Try
  112.  
  113.    End Sub
  114.  
  115.    ''' <summary>
  116.    ''' Determines whether the current file is possibly corrupted.
  117.    ''' </summary>
  118.    Public Function IsCorrupt() As Boolean
  119.  
  120.        Me.CheckTagFile()
  121.        Return Me.TagFile.PossiblyCorrupt
  122.  
  123.    End Function
  124.  
  125.    ''' <summary>
  126.    ''' Determines whether the current file can be written.
  127.    ''' </summary>
  128.    Public Function IsWriteable() As Boolean
  129.  
  130.        Me.CheckTagFile()
  131.        Return Me.TagFile.Writeable
  132.  
  133.    End Function
  134.  
  135.    ''' <summary>
  136.    ''' Get TagTypes of file.
  137.    ''' </summary>
  138.    Public Function GetTags() As String
  139.  
  140.        Me.CheckTagFile()
  141.        Return Me.TagFile.TagTypesOnDisk.ToString
  142.  
  143.    End Function
  144.  
  145.    ''' <summary>
  146.    ''' Gets the Title tag of the current file.
  147.    ''' </summary>
  148.    Public Function GetTitle() As String
  149.  
  150.        Me.CheckTagFile()
  151.        Return Me.TagFile.Tag.Title
  152.  
  153.    End Function
  154.  
  155.    ''' <summary>
  156.    ''' Gets the Artist tag of the current file.
  157.    ''' </summary>
  158.    Public Function GetArtist() As String
  159.  
  160.        Me.CheckTagFile()
  161.  
  162.        If Me.TagFile.Tag.Performers.Count <> 0 Then
  163.            Return Me.TagFile.Tag.Performers(0)
  164.  
  165.        Else
  166.            Return String.Empty
  167.  
  168.        End If
  169.  
  170.    End Function
  171.  
  172.    ''' <summary>
  173.    ''' Gets the Album tag of the current file.
  174.    ''' </summary>
  175.    Public Function GetAlbum() As String
  176.  
  177.        Me.CheckTagFile()
  178.        Return Me.TagFile.Tag.Album
  179.  
  180.    End Function
  181.  
  182.    ''' <summary>
  183.    ''' Gets the Genre tag of the current file.
  184.    ''' </summary>
  185.    Public Function GetGenre() As String
  186.  
  187.        Me.CheckTagFile()
  188.        If Me.TagFile.Tag.Genres.Count <> 0 Then
  189.            Return Me.TagFile.Tag.Genres(0)
  190.  
  191.        Else
  192.            Return String.Empty
  193.  
  194.        End If
  195.  
  196.    End Function
  197.  
  198.    ''' <summary>
  199.    ''' Gets the Year tag of the current file.
  200.    ''' </summary>
  201.    Public Function GetYear() As String
  202.  
  203.        Me.CheckTagFile()
  204.        Return Me.TagFile.Tag.Year.ToString
  205.  
  206.    End Function
  207.  
  208.    ''' <summary>
  209.    ''' Sets a Tag field.
  210.    ''' </summary>
  211.    Public Sub SetTag(ByVal fieldSetter As Action(Of TagLib.File))
  212.  
  213.        Me.CheckTagFile()
  214.        If Not Me.IsCorrupt AndAlso Me.IsWriteable Then
  215.  
  216.            Try
  217.                fieldSetter(TagFile)
  218.  
  219.            Catch ex As Exception
  220.                Throw
  221.  
  222.            End Try
  223.  
  224.            Me.SaveFile()
  225.  
  226.        End If
  227.  
  228.    End Sub
  229.  
  230.    ''' <summary>
  231.    ''' Sets multiple Tag fields.
  232.    ''' </summary>
  233.    Public Sub SetTags(ByVal fieldSetter() As Action(Of TagLib.File))
  234.  
  235.        Me.CheckTagFile()
  236.        If Not Me.IsCorrupt AndAlso Me.IsWriteable Then
  237.  
  238.            For Each field As Action(Of TagLib.File) In fieldSetter
  239.  
  240.                Try
  241.                    field(TagFile)
  242.  
  243.                Catch ex As Exception
  244.                    Throw
  245.  
  246.                End Try
  247.  
  248.            Next field
  249.  
  250.            Me.SaveFile()
  251.  
  252.        End If
  253.  
  254.    End Sub
  255.  
  256.    ''' <summary>
  257.    ''' Remove a Tag from the current file.
  258.    ''' </summary>
  259.    ''' <param name="tagTypes">The tag types to remove from file.</param>
  260.    Public Sub RemoveTag(ByVal tagTypes As TagTypes)
  261.  
  262.        Me.CheckTagFile()
  263.        If Not Me.IsCorrupt AndAlso Me.IsWriteable Then
  264.  
  265.            Try
  266.                Me.TagFile.RemoveTags(tagTypes)
  267.  
  268.            Catch ex As Exception
  269.                Throw
  270.  
  271.            End Try
  272.  
  273.            Me.SaveFile()
  274.  
  275.        End If
  276.  
  277.    End Sub
  278.  
  279. #End Region
  280.  
  281. #Region " Private Methods "
  282.  
  283.    ''' <summary>
  284.    ''' Saves the current file.
  285.    ''' </summary>
  286.    Private Sub SaveFile()
  287.  
  288.        Me.CheckTagFile()
  289.  
  290.        Try
  291.            Me.TagFile.Save()
  292.  
  293.        Catch ex As Exception
  294.            Throw
  295.  
  296.        End Try
  297.  
  298.    End Sub
  299.  
  300.    ''' <summary>
  301.    ''' Checks whether a <see cref="TagLib.File"/> object is loaded.
  302.    ''' </summary>
  303.    Private Sub CheckTagFile()
  304.  
  305.        If Me.TagFile Is Nothing Then
  306.  
  307.            Throw New Exception("Any file is loaded.")
  308.  
  309.        End If
  310.  
  311.    End Sub
  312.  
  313. #End Region
  314.  
  315. End Class
  316.  
  317. #End Region
  318.  



Ejemplo (...un poco cutre por el momento) de cmo utilizar un KryptonSeparator, del set de controles Krypton: http://www.componentfactory.com/toolkit_utilitycontrols.php



Código
  1.        ''' <summary>
  2.        ''' Handles the SplitterMoving event of the KryptonSeparator1 control.
  3.        ''' </summary>
  4.        ''' <param name="sender">The source of the event.</param>
  5.        ''' <param name="e">The <see cref="SplitterCancelEventArgs"/> instance containing the event data.</param>
  6.        Private Sub KryptonSeparator1_SplitterMoving(ByVal sender As Object, ByVal e As SplitterCancelEventArgs) _
  7.        Handles KryptonSeparator1.SplitterMoving
  8.  
  9.            Dim separator As KryptonSeparator = DirectCast(sender, KryptonSeparator)
  10.            Dim leftCtrl As Control = Me.ListBox1
  11.            Dim rightCtrl As Control = Me.ListBox2
  12.  
  13.            If (e.MouseCursorX > 0) _
  14.            AndAlso Not ((rightCtrl.Size.Width - e.MouseCursorX) < rightCtrl.MinimumSize.Width) Then
  15.  
  16.                separator.Location = New Point(separator.Location.X + e.MouseCursorX, separator.Location.Y)
  17.                leftCtrl.Width += e.MouseCursorX
  18.                rightCtrl.Width -= e.MouseCursorX
  19.                rightCtrl.Left = separator.Right
  20.  
  21.            ElseIf (e.MouseCursorX < 0) _
  22.            AndAlso Not ((leftCtrl.Size.Width + e.MouseCursorX - separator.Width) < leftCtrl.MinimumSize.Width) Then
  23.  
  24.                separator.Location = New Point(separator.Location.X - separator.Width, separator.Location.Y)
  25.                leftCtrl.Width -= separator.Width
  26.                rightCtrl.Width += separator.Width
  27.                rightCtrl.Left = separator.Right
  28.  
  29.            End If
  30.  
  31.        End Sub
  32.  
6373  Foros Generales / Sugerencias y dudas sobre el Foro / Re: Subforo de programación de juegos? en: 29 Noviembre 2014, 13:21 pm
1) Estoy de acuerdo en que se haga una sección donde se pueda ayudar en la utilización de aplicaciones como: "Unity, UDK, CryEngine, Flash, GameMaker, etc" para el desarrollo de juegos.
Cómo podría ser la sección de Diseño Grafico, donde más que nada se formulan dudas de la utilización de Photoshop, o al menos eso es lo que siempre vi allí.

2) Por otro lado es algo que entra en conflicto con mis ideas, ya que en mi opinión los subforos de programación deben clasificarse según lenguajes de programación, no según temáticas de software/programación ni mucho menos aplicaciones, la razón es simple, temáticas hay miles y entre otras cosas no dariamos a basto para el mantenimiento, por no decir que algunas temáticas llegarían a tener con suerte solamente 1 mensaje publicado.

Aparte de esto, la programación de juegos no se queda en la utilización de esas aplicaciones, sino en los lenguajes que se han de utilizar para elaborar las entrañas del juego, bien lo sabes, al menos en Unity pude comprobar que se debe recurrir a lenguajes como C#, Python, etc. Ya existe un subforo para cada uno de los lenguajes de programación más usados hoy en dia.

Yo creo que los posibles usuarios que estén aquí y que estén haciendo algo relacionado con programación de juegos no han preguntado nada, por la posible ausencia de un subforo dedicado a dicha temática.
Crees erroneamente, ya que los usuarios formulan sus preguntas de la temática que sea donde corresponde, es decir, en el subforo del lenguaje que estén utilizando.
Cómo sabes modero tres secciones de programación, y puedo decir que si, he visto varias preguntas relacionadas con la programación de juegos, de hecho hay una duda muy reciente sobre la programación de juegos en Python.

Saludos!
6374  Programación / Scripting / Re: Batch - Guardar un resultado en un txt (No es tan fácil) en: 28 Noviembre 2014, 18:01 pm
He reproducido las circunstancias del problema que describes, para ello he desarrollado una mini-aplicación CommandLine que simplemente genera el mismo string con los caracteres ilegales "<" ">", pero a mi me funciona correctamente el commando de redirección que a ti al parecer no te funciona.

De todas formas, prueba a usar la sintaxis más adecuada:
Código:
("fastboot.exe" oem get_unlock_data)1>> ".\FastbootCodigo.txt"

Si eso no te funciona entonces quizás lo más probable es que la aplicación no esté enviando los datos a la salida estándar, así que prueba a redirigir la salida de error:
Código:
("fastboot.exe" oem get_unlock_data)2>> ".\FastbootCodigo.txt"

Saludos.
6375  Sistemas Operativos / Windows / Re: windows 10 incluira un package manager estilo linux llamado oneget en: 28 Noviembre 2014, 12:40 pm
Para llamarse Microsoft se han currado muy pero que muy poco la interfaz de usuario de dicha característica que obligan a la utilización e interfaz de PS para el proceso de descarga e instalación, pf, los newbies no sabrán ni localizar PS ni ponerse a escribir las instrucciones necesarias en la consola para descargar paquetes sin una GUI "pa tontos", hacer las cosas de esa manera no es nada propio de Microsoft, y luego está lo de Windows "10".

Saludos!
6376  Foros Generales / Foro Libre / Re: Necesito localizar a alguien que amenaza por llamadas en: 28 Noviembre 2014, 05:07 am
Bueno, visto que no quieres acudir a quien deberías acudir y prefieres hacer de detective por ti mismo, te cuento:

Puedes probar con distintos servicios online tanto gratis como de pago que recopilan bases de datos de teléfonos móvil, no te costará nada encontrar estos servicios en Google, obviamente los servicios de pago te darían mayores posibilidades de éxito en tu búsqueda, este método de búsqueda se denomina Reverse Phone Lookup, pero te advierto que es un método muy ineficaz debido a que que cada día miles de personas renuevan/tiran o se compran un mvl y suelen ser servicios que obtienen los datos desde muchas y diferentes bases de datos (ya que no existe una MEGA-db pública donde se recopile la información de todos los telfs de La Tierra, bueno, quizás la CIA, jaja, aunque eso sería privado, claro...), de todas formas es el único medio público de localización que puede usar una persona "normal" (al menos que yo sepa), a menos que acudas a la policia o a un detective privado (no tienes excusa para eso, jeje :P).

Saludos
6377  Foros Generales / Foro Libre / Re: Necesito localizar a alguien que amenaza por llamadas en: 28 Noviembre 2014, 04:59 am
necesito localizar a alguien que me llama amenazando de muerte y dice que me va a matar...

dice ser el tio de mi novia...
dice que no es de Buenos Aires...
Dice que tiene el 54 por que es de una empresa...
el dice ser de Salta

Para querer matarte parece que está intimando bastante xD

((En su numero cuando llama aparece que es de Buenos Aires, por el 54, pero me dice que no, ¿puede estar mintiendome?))

¿Es que cabe la duda de que un individuo que te llama para decir sandeces te pueda mentir?.

Ahora en serio, disculpa que me lo tome a broma, pero si a mi me llama un desconocido desde otro país y me amenaza de muerte lo más seguro es que se esté burlando de mi y no tenga el valor necesario para burlarse cara a cara, ¿en serio crees que merece la importancia que le estás dando al asunto?, según la información que has proporcionado al explicar el "incidente" yo no creo que tu vida corra peligro.

Si temes por tu vida entonces llama a la policia, si es que no entiendo este tipo de posts... ¿por qué no acudes a la policia para que ellos se encarguen de rastrear al presunto asesino si lo consideran necesario?.

Saludos!
6378  Sistemas Operativos / Windows / Re: Quien me enseña a modificar windows 8.1? en: 28 Noviembre 2014, 04:44 am
Agregar programas es tan sencillo como instalarlos.
No existe otra posible respuesta, jajaja.

Quien me enseña a ... o modificar uno que ya esta hecho?
Si por "modificar" te refieres a modificar el comportamiento/funcionamiento de una aplicación sin tener acceso al código fuente entonces creo que no sabes donde te estás adentrando, te espera un largo aprendizaje por el camino de la Ingeniería Inversa, en el foro tienes una sección dedicada al tema si te decides, pero no esperes que nadie te enseñe a "como modificar un programa" y menos de la noche a la mañana... como mucho te pueden recomendar libros y largas lecturas que debes aprender y entender, y por supuesto también te ayudarán donde te quedes atascado.

Saludos!
6379  Foros Generales / Foro Libre / Re: TeamViewer - control remoto de ordenadores, que es? en: 27 Noviembre 2014, 23:11 pm
Ay señor...

No soy para nada ningún experto en el diseño de Malware pero en mi opinión dudo muchísimo que eso pudiese ocurrir solamente por utilizar TeamViewer, ¿que el virus se envie por si solo en algún paquete de los que estas recibiendo por parte de TeamViewer y se auto-ejecute en tu equipo?, ni que esto fuera el tan explotado eMule u otro peer2peer para la propagación de virus, Teamviewer es un programa profesional y con sus medidas de seguridad implementadas bajo una conexión "segura".

Si me dijeras que TeamViewer crease una conexión a un equipo remoto en el PC donde te conectas (cosa que no hace), y ese individuo estuviese infectado con un virus que tuviese un spread implementado capaz de propagarse remotamente buscando conexiones de equipos remotos instalados, entonces vale, pero 1 de cada 1.000.000 de virus deben ser así de eficientes (por decir un número aleatorio bajo mi percepción, vaya).

Quizás me he equivocado en algún concepto de lo que he mencionado ya que como he dicho no soy experto en Malware, desconozco realmente si un virus puede propagarse mediante una conexión establecida entre 2 clientes de TeamViewer, pero nunca he escuchado ese caso, demasiadas preocupaciones teneis... de verdad, DEMASIADAS.

Además, los AntiVirus están para algo.

Saludos!

6380  Programación / .NET (C#, VB.NET, ASP) / Re: ¿Cómo puedo insertar un listbox en un messagebox? VB.NET 2010 en: 27 Noviembre 2014, 22:41 pm
Un MessageBox no es más que un diálogo, y como tal puedes hallar el handle (hwnd) de su ventana principal, redimensionar la ventana y enumerar sus controles para quizás hacer lo mismo y dejar espacio para tu nuevo control, por ende puedes posicionar "X" control relativamente en el rectangle de dicho dialog.

Pero esa idea es una locura, lo mejor es que hagas un nuevo Form y lo personalices de forma manual con el aspecto típico de un MessageBox (hay muchos ejemplos en Google) y allí añadas los controles que desees, y luego utilices ese Form como un Dialog, ya que un MessageBox puede ser cambiado o extendido, sí, pero es una pesadilla ya que requiere bastante esfuerzo y mucho P/Invoking para realizar pequeñas modificaciones, de todas formas te muestro un ejemplo que desarrollé donde deberías poder encontrar todo lo necesario para tus intenciones, pero como ya dije, no te recomiendo este enfoque para tus necesidades:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 27-November-2014
  4. ' ***********************************************************************
  5. ' <copyright file="CenteredMessageBox.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Using New CenteredMessageBox(ownerForm:=Me,
  13. '                             textFont:=New Font("Lucida Console", Font.SizeInPoints, FontStyle.Bold),
  14. '                             timeOut:=2500)
  15. '
  16. '    MessageBox.Show("Text", "Title", MessageBoxButtons.OK, MessageBoxIcon.Information)
  17. '
  18. 'End Using
  19.  
  20. #End Region
  21.  
  22. #Region " Option Statements "
  23.  
  24. Option Explicit On
  25. Option Strict On
  26. Option Infer Off
  27.  
  28. #End Region
  29.  
  30. #Region " Imports "
  31.  
  32. Imports System.Drawing
  33. Imports System.Runtime.InteropServices
  34. Imports System.Text
  35. Imports System.Windows.Forms
  36. Imports System.ComponentModel
  37.  
  38. #End Region
  39.  
  40. #Region " Centered MessageBox "
  41.  
  42. Namespace Tools
  43.  
  44.    ''' <summary>
  45.    ''' A customized <see cref="MessageBox"/>.
  46.    ''' This class cannot be inherited.
  47.    ''' </summary>
  48.    Friend NotInheritable Class CenteredMessageBox : Implements IDisposable
  49.  
  50. #Region " Properties "
  51.  
  52.        ''' <summary>
  53.        ''' Gets the messagebox main window handle (hwnd).
  54.        ''' </summary>
  55.        ''' <value>The messagebox main window handle (hwnd).</value>
  56.        Friend ReadOnly Property MessageBoxWindowHandle As IntPtr
  57.            Get
  58.                Return Me.messageBoxWindowHandle1
  59.            End Get
  60.        End Property
  61.        ''' <summary>
  62.        ''' The messagebox main window handle (hwnd).
  63.        ''' </summary>
  64.        Private messageBoxWindowHandle1 As IntPtr
  65.  
  66.        ''' <summary>
  67.        ''' Gets the owner <see cref="Form"/> to center the <see cref="CenteredMessageBox"/>.
  68.        ''' </summary>
  69.        ''' <value>The owner <see cref="Form"/> to center the <see cref="CenteredMessageBox"/>.</value>
  70.        Friend ReadOnly Property OwnerForm As Form
  71.            Get
  72.                Return Me.ownerForm1
  73.            End Get
  74.        End Property
  75.        ''' <summary>
  76.        ''' The owner <see cref="Form"/> to center the <see cref="CenteredMessageBox"/>
  77.        ''' </summary>
  78.        Private ownerForm1 As Form
  79.  
  80.        ''' <summary>
  81.        ''' Gets the <see cref="Font"/> used to display the <see cref="CenteredMessageBox"/> text.
  82.        ''' </summary>
  83.        ''' <value>The <see cref="Font"/> used to display the <see cref="CenteredMessageBox"/> text.</value>
  84.        Friend ReadOnly Property Font As Font
  85.            Get
  86.                Return Me.font1
  87.            End Get
  88.        End Property
  89.        ''' <summary>
  90.        ''' The <see cref="Font"/> used to display the <see cref="CenteredMessageBox"/> text.
  91.        ''' </summary>
  92.        Private ReadOnly font1 As Font
  93.  
  94.        ''' <summary>
  95.        ''' Gets the time interval to auto-close this <see cref="CenteredMessageBox"/>, in milliseconds.
  96.        ''' Default value is '0', which means Infinite.
  97.        ''' </summary>
  98.        Friend ReadOnly Property TimeOut As Integer
  99.            Get
  100.                Return Me.timeOut1
  101.            End Get
  102.        End Property
  103.        ''' <summary>
  104.        ''' The time interval to auto-close this <see cref="CenteredMessageBox"/>, in milliseconds.
  105.        ''' Default value is '0', which means Infinite.
  106.        ''' </summary>
  107.        Private ReadOnly timeOut1 As Integer = 0
  108.  
  109. #End Region
  110.  
  111. #Region " Objects "
  112.  
  113.        ''' <summary>
  114.        ''' A <see cref="Windows.Forms.Timer"/> that keeps track of <see cref="TimeOut"/> value to close this <see cref="CenteredMessageBox"/>.
  115.        ''' </summary>
  116.        Private WithEvents timeoutTimer As Timer
  117.  
  118.        ''' <summary>
  119.        ''' Keeps track of the current amount of tries to find this <see cref="CenteredMessageBox"/> dialog.
  120.        ''' </summary>
  121.        Private tries As Integer
  122.  
  123. #End Region
  124.  
  125. #Region " P/Invoke "
  126.  
  127.        ''' <summary>
  128.        ''' Platform Invocation methods (P/Invoke), access unmanaged code.
  129.        ''' This class does not suppress stack walks for unmanaged code permission.
  130.        ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
  131.        ''' This class is for methods that can be used anywhere because a stack walk will be performed.
  132.        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
  133.        ''' </summary>
  134.        Protected NotInheritable Class NativeMethods
  135.  
  136. #Region " Functions "
  137.  
  138.            ''' <summary>
  139.            ''' Retrieves the thread identifier of the calling thread.
  140.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms683183%28v=vs.85%29.aspx
  141.            ''' </summary>
  142.            ''' <returns>The thread identifier of the calling thread.</returns>
  143.            <DllImport("kernel32.dll", SetLastError:=False)>
  144.            Protected Friend Shared Function GetCurrentThreadId() As Integer
  145.            End Function
  146.  
  147.            ''' <summary>
  148.            ''' Enumerates all nonchild windows associated with a thread by passing the handle to each window,
  149.            ''' in turn, to an application-defined callback function.
  150.            ''' <see cref="EnumThreadWindows"/> continues until the last window is enumerated or the callback function returns <c>false</c>.
  151.            ''' To enumerate child windows of a particular window, use the EnumChildWindows function.
  152.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633495%28v=vs.85%29.aspx
  153.            ''' </summary>
  154.            ''' <param name="dwThreadId">The identifier of the thread whose windows are to be enumerated.</param>
  155.            ''' <param name="lpfn">A pointer to an application-defined callback function.</param>
  156.            ''' <param name="lParam">An application-defined value to be passed to the callback function.</param>
  157.            ''' <returns>
  158.            ''' <c>true</c> if the callback function returns <c>true</c> for all windows in the thread specified by dwThreadId parameter.
  159.            ''' <c>false</c> if the callback function returns <c>false</c> on any enumerated window,
  160.            ''' or if there are no windows found in the thread specified by dwThreadId parameter.</returns>
  161.            <DllImport("user32.dll", SetLastError:=False)>
  162.            Protected Friend Shared Function EnumThreadWindows(
  163.                      ByVal dwThreadId As Integer,
  164.                      ByVal lpfn As NativeMethods.EnumThreadWndProc,
  165.                      ByVal lParam As IntPtr
  166.            ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  167.            End Function
  168.  
  169.            ''' <summary>
  170.            ''' Retrieves the name of the class to which the specified window belongs.
  171.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633582%28v=vs.85%29.aspx
  172.            ''' </summary>
  173.            ''' <param name="hWnd">A handle to the window and, indirectly, the class to which the window belongs.</param>
  174.            ''' <param name="buffer">The class name string.</param>
  175.            ''' <param name="buflen">
  176.            ''' The length of the lpClassName buffer, in characters.
  177.            ''' The buffer must be large enough to include the terminating null character;
  178.            ''' otherwise, the class name string is truncated to nMaxCount-1 characters.
  179.            ''' </param>
  180.            ''' <returns>
  181.            ''' If the function succeeds, the return value is the number of characters copied to the buffer,
  182.            ''' not including the terminating null character.
  183.            ''' If the function fails, the return value is 0.
  184.            ''' </returns>
  185.            <DllImport("user32.dll", SetLastError:=False, CharSet:=CharSet.Unicode)>
  186.            Protected Friend Shared Function GetClassName(
  187.                      ByVal hWnd As IntPtr,
  188.                      ByVal buffer As StringBuilder,
  189.                      ByVal buflen As Integer
  190.            ) As Integer
  191.            End Function
  192.  
  193.            ''' <summary>
  194.            ''' Retrieves a handle to a control in the specified dialog box.
  195.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms645481%28v=vs.85%29.aspx
  196.            ''' </summary>
  197.            ''' <param name="hWnd">A handle to the dialog box that contains the control.</param>
  198.            ''' <param name="item">The identifier of the control to be retrieved.</param>
  199.            ''' <returns>
  200.            ''' If the function succeeds, the return value is the window handle of the specified control.
  201.            ''' If the function fails, the return value is <see cref="IntPtr.Zero"/>,
  202.            ''' indicating an invalid dialog box handle or a nonexistent control
  203.            ''' </returns>
  204.            <DllImport("user32.dll", SetLastError:=False)>
  205.            Protected Friend Shared Function GetDlgItem(
  206.                      ByVal hWnd As IntPtr,
  207.                      ByVal item As Integer
  208.            ) As IntPtr
  209.            End Function
  210.  
  211.            ''' <summary>
  212.            ''' Retrieves the dimensions of the bounding rectangle of the specified window.
  213.            ''' The dimensions are given in screen coordinates that are relative to the upper-left corner of the screen.
  214.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633519%28v=vs.85%29.aspx
  215.            ''' </summary>
  216.            ''' <param name="hWnd">A handle to the window.</param>
  217.            ''' <param name="rc">
  218.            ''' A pointer to a <see cref="RECT"/> structure that receives the screen coordinates of
  219.            ''' the upper-left and lower-right corners of the window.
  220.            ''' </param>
  221.            ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  222.            <DllImport("user32.dll", SetLastError:=False)>
  223.            Protected Friend Shared Function GetWindowRect(
  224.                      ByVal hWnd As IntPtr,
  225.                      ByRef rc As Rect
  226.            ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  227.            End Function
  228.  
  229.            ''' <summary>
  230.            ''' Destroys the specified window.
  231.            ''' The function sends WM_DESTROY and WM_NCDESTROY messages to the window to deactivate it and remove the keyboard focus from it.
  232.            ''' The function also destroys the window's menu, flushes the thread message queue, destroys timers, removes clipboard ownership,
  233.            ''' and breaks the clipboard viewer chain (if the window is at the top of the viewer chain).
  234.            ''' If the specified window is a parent or owner window,
  235.            ''' DestroyWindow automatically destroys the associated child or owned windows when it destroys the parent or owner window.
  236.            ''' The function first destroys child or owned windows, and then it destroys the parent or owner window.
  237.            ''' DestroyWindow also destroys modeless dialog boxes created by the CreateDialog function.
  238.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632682%28v=vs.85%29.aspx
  239.            ''' </summary>
  240.            ''' <param name="hwnd">Handle to the window to be destroyed.</param>
  241.            ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  242.            <DllImport("user32.dll", SetLastError:=False)>
  243.            Protected Friend Shared Function DestroyWindow(
  244.                      ByVal hwnd As IntPtr
  245.            ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  246.            End Function
  247.  
  248.            ''' <summary>
  249.            ''' Changes the position and dimensions of the specified window.
  250.            ''' For a top-level window, the position and dimensions are relative to the upper-left corner of the screen.
  251.            ''' For a child window, they are relative to the upper-left corner of the parent window's client area.
  252.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633534%28v=vs.85%29.aspx
  253.            ''' </summary>
  254.            ''' <param name="hWnd">A handle to the window.</param>
  255.            ''' <param name="x">The new position of the left side of the window.</param>
  256.            ''' <param name="y">The new position of the top of the window.</param>
  257.            ''' <param name="width">The new width of the window.</param>
  258.            ''' <param name="height">The new height of the window.</param>
  259.            ''' <param name="repaint">
  260.            ''' Indicates whether the window is to be repainted.
  261.            ''' If this parameter is TRUE, the window receives a message.
  262.            ''' If the parameter is FALSE, no repainting of any kind occurs.
  263.            ''' This applies to the client area, the nonclient area (including the title bar and scroll bars),
  264.            ''' and any part of the parent window uncovered as a result of moving a child window.
  265.            ''' </param>
  266.            ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  267.            <DllImport("user32.dll", SetLastError:=False)>
  268.            Protected Friend Shared Function MoveWindow(
  269.                      ByVal hWnd As IntPtr,
  270.                      ByVal x As Integer,
  271.                      ByVal y As Integer,
  272.                      ByVal width As Integer,
  273.                      ByVal height As Integer,
  274.                      ByVal repaint As Boolean
  275.            ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  276.            End Function
  277.  
  278.            ''' <summary>
  279.            ''' Changes the size, position, and Z order of a child, pop-up, or top-level window.
  280.            ''' These windows are ordered according to their appearance on the screen.
  281.            ''' The topmost window receives the highest rank and is the first window in the Z order.
  282.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
  283.            ''' </summary>
  284.            ''' <param name="hWnd">A handle to the window.</param>
  285.            ''' <param name="hWndInsertAfter">A handle to the window to precede the positioned window in the Z order.</param>
  286.            ''' <param name="x">The new position of the left side of the window, in client coordinates.</param>
  287.            ''' <param name="y">The new position of the top of the window, in client coordinates.</param>
  288.            ''' <param name="cx">The new width of the window, in pixels.</param>
  289.            ''' <param name="cy">The new height of the window, in pixels.</param>
  290.            ''' <param name="uFlags">The window sizing and positioning flags.</param>
  291.            ''' <returns><c>true</c> if the function succeeds, <c>false</c> otherwise.</returns>
  292.            <DllImport("user32.dll", SetLastError:=True)> _
  293.            Protected Friend Shared Function SetWindowPos(
  294.                      ByVal hWnd As IntPtr,
  295.                      ByVal hWndInsertAfter As IntPtr,
  296.                      ByVal x As Integer,
  297.                      ByVal y As Integer,
  298.                      ByVal cx As Integer,
  299.                      ByVal cy As Integer,
  300.                      ByVal uFlags As SetWindowPosFlags
  301.            ) As <MarshalAs(UnmanagedType.Bool)> Boolean
  302.            End Function
  303.  
  304.            ''' <summary>
  305.            ''' Sends the specified message to a window or windows.
  306.            ''' The <see cref="SendMessage"/> function calls the window procedure for the specified window and
  307.            ''' does not return until the window procedure has processed the message.
  308.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950%28v=vs.85%29.aspx
  309.            ''' </summary>
  310.            ''' <param name="hWnd">A handle to the window whose window procedure will receive the message.</param>
  311.            ''' <param name="msg">The windows message to be sent.</param>
  312.            ''' <param name="wParam">Additional message-specific information.</param>
  313.            ''' <param name="lParam">Additional message-specific information.</param>
  314.            ''' <returns>The result of the message processing; it depends on the message sent.</returns>
  315.            <DllImport("user32.dll", SetLastError:=False)>
  316.            Protected Friend Shared Function SendMessage(
  317.                      ByVal hWnd As IntPtr,
  318.                      ByVal msg As WindowsMessages,
  319.                      ByVal wParam As IntPtr,
  320.                      ByVal lParam As IntPtr
  321.            ) As IntPtr
  322.            End Function
  323.  
  324. #End Region
  325.  
  326. #Region " Callbacks "
  327.  
  328.            ''' <summary>
  329.            ''' An application-defined callback function used with the <see cref="EnumThreadWindows"/> function.
  330.            ''' It receives the window handles associated with a thread.
  331.            ''' The WNDENUMPROC type defines a pointer to this callback function.
  332.            ''' <see cref="EnumThreadWndProc"/> is a placeholder for the application-defined function name
  333.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633496%28v=vs.85%29.aspx
  334.            ''' </summary>
  335.            ''' <param name="hWnd">A handle to a window associated with the thread specified in the <see cref="EnumThreadWindows"/> function.</param>
  336.            ''' <param name="lParam">The application-defined value given in the <see cref="EnumThreadWindows"/> function.</param>
  337.            ''' <returns>
  338.            ''' To continue enumeration, the callback function must return <c>true</c>;
  339.            ''' To stop enumeration, it must return <c>false</c>.
  340.            ''' </returns>
  341.            Protected Friend Delegate Function EnumThreadWndProc(
  342.                      ByVal hWnd As IntPtr,
  343.                      ByVal lParam As IntPtr
  344.            ) As Boolean
  345.  
  346. #End Region
  347.  
  348. #Region " Enumerations "
  349.  
  350.            ''' <summary>
  351.            ''' Specifies a System-Defined Message.
  352.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644927%28v=vs.85%29.aspx#system_defined
  353.            ''' </summary>
  354.            <Description("Enum used for 'SendMessage' function.")>
  355.            Protected Friend Enum WindowsMessages As Integer
  356.  
  357.                ' **************************************
  358.                ' NOTE:
  359.                ' This enumeration is partially defined.
  360.                ' **************************************
  361.  
  362.                ''' <summary>
  363.                ''' Sets the font that a control is to use when drawing text.
  364.                ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632642%28v=vs.85%29.aspx
  365.                ''' </summary>
  366.                WM_SETFONT = &H30
  367.  
  368.                ''' <summary>
  369.                ''' Retrieves the font with which the control is currently drawing its text.
  370.                ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632624%28v=vs.85%29.aspx
  371.                ''' </summary>
  372.                WM_GETFONT = &H31
  373.  
  374.            End Enum
  375.  
  376.            ''' <summary>
  377.            ''' Specifies the window sizing and positioning flags.
  378.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545%28v=vs.85%29.aspx
  379.            ''' </summary>
  380.            <FlagsAttribute>
  381.            <Description("Enum used for 'SetWindowPos' function.")>
  382.            Protected Friend Enum SetWindowPosFlags As UInteger
  383.  
  384.                ' **************************************
  385.                ' NOTE:
  386.                ' This enumeration is partially defined.
  387.                ' **************************************
  388.  
  389.                ''' <summary>
  390.                ''' Indicates any flag.
  391.                ''' </summary>
  392.                None = &H0UI
  393.  
  394.            End Enum
  395.  
  396. #End Region
  397.  
  398. #Region " Structures "
  399.  
  400.            ''' <summary>
  401.            ''' Defines the coordinates of the upper-left and lower-right corners of a rectangle.
  402.            ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/dd162897%28v=vs.85%29.aspx
  403.            ''' </summary>
  404.            <Description("Structure used for 'GetWindowRect' function.")>
  405.            Protected Friend Structure Rect
  406.  
  407.                ''' <summary>
  408.                ''' The x-coordinate of the upper-left corner of the rectangle.
  409.                ''' </summary>
  410.                Friend Left As Integer
  411.  
  412.                ''' <summary>
  413.                ''' The y-coordinate of the upper-left corner of the rectangle.
  414.                ''' </summary>
  415.                Friend Top As Integer
  416.  
  417.                ''' <summary>
  418.                ''' The x-coordinate of the lower-right corner of the rectangle.
  419.                ''' </summary>
  420.                Friend Right As Integer
  421.  
  422.                ''' <summary>
  423.                ''' The y-coordinate of the lower-right corner of the rectangle.
  424.                ''' </summary>
  425.                Friend Bottom As Integer
  426.  
  427.            End Structure
  428.  
  429. #End Region
  430.  
  431.        End Class
  432.  
  433. #End Region
  434.  
  435. #Region " Constructors "
  436.  
  437.        ''' <summary>
  438.        ''' Initializes a new instance of the <see cref="CenteredMessageBox"/> class.
  439.        ''' </summary>
  440.        ''' <param name="ownerForm">The form that owns this <see cref="CenteredMessageBox"/>.</param>
  441.        ''' <param name="TextFont">The <see cref="Font"/> used to display the text of this <see cref="CenteredMessageBox"/>.</param>
  442.        ''' <param name="TimeOut">
  443.        ''' The time interval to auto-close this <see cref="CenteredMessageBox"/>, in milliseconds;
  444.        ''' Default value is '0', which means Infinite.
  445.        ''' </param>
  446.        Public Sub New(ByVal ownerForm As Form,
  447.                       Optional textFont As Font = Nothing,
  448.                       Optional timeOut As Integer = 0I)
  449.  
  450.            Me.ownerForm1 = ownerForm
  451.            Me.font1 = textFont
  452.            Me.timeOut1 = timeOut
  453.            Me.ownerForm1.BeginInvoke(New MethodInvoker(AddressOf Me.FindDialog))
  454.  
  455.        End Sub
  456.  
  457.        ''' <summary>
  458.        ''' Prevents a default instance of the <see cref="CenteredMessageBox"/> class from being created.
  459.        ''' </summary>
  460.        Private Sub New()
  461.        End Sub
  462.  
  463. #End Region
  464.  
  465. #Region " Private Methods "
  466.  
  467.        ''' <summary>
  468.        ''' Finds the <see cref="CenteredMessageBox"/> dialog window.
  469.        ''' </summary>
  470.        Private Sub FindDialog()
  471.  
  472.            ' Enumerate windows to find the message box
  473.            If Me.tries < 0 Then
  474.                Return
  475.            End If
  476.  
  477.            Dim callback As New NativeMethods.EnumThreadWndProc(AddressOf Me.CheckWindow)
  478.  
  479.            If NativeMethods.EnumThreadWindows(NativeMethods.GetCurrentThreadId(), callback, IntPtr.Zero) Then
  480.  
  481.                If Threading.Interlocked.Increment(Me.tries) < 10 Then
  482.                    Me.ownerForm1.BeginInvoke(New MethodInvoker(AddressOf Me.FindDialog))
  483.                End If
  484.  
  485.            End If
  486.  
  487.            If Me.timeOut1 > 0 Then
  488.  
  489.                Me.timeoutTimer = New Timer With
  490.                                  {
  491.                                      .Interval = Me.timeOut1,
  492.                                      .Enabled = True
  493.                                  }
  494.  
  495.                Me.timeoutTimer.Start()
  496.  
  497.            End If
  498.  
  499.        End Sub
  500.  
  501.        ''' <summary>
  502.        ''' Checks whether the specified window is our <see cref="CenteredMessageBox"/> dialog.
  503.        ''' </summary>
  504.        ''' <param name="hWnd">A handle to the window to check.</param>
  505.        ''' <param name="lParam">The application-defined value given in the <see cref="NativeMethods.EnumThreadWindows"/> function.</param>
  506.        ''' <returns>
  507.        ''' <c>true</c> the specified window is our <see cref="CenteredMessageBox"/> dialog, <c>false</c> otherwise.
  508.        ''' </returns>
  509.        Private Function CheckWindow(ByVal hWnd As IntPtr,
  510.                                     ByVal lParam As IntPtr) As Boolean
  511.  
  512.            ' Checks if <hWnd> is a dialog
  513.            Dim sb As New StringBuilder(260)
  514.            NativeMethods.GetClassName(hWnd, sb, sb.Capacity)
  515.            If sb.ToString() <> "#32770" Then
  516.                Return True
  517.            End If
  518.  
  519.            ' Get the control that displays the text.
  520.            Dim hText As IntPtr = NativeMethods.GetDlgItem(hWnd, &HFFFFI)
  521.            Me.messageBoxWindowHandle1 = hWnd
  522.  
  523.            ' Get the dialog Rect.
  524.            Dim frmRect As New Rectangle(Me.ownerForm1.Location, Me.ownerForm1.Size)
  525.            Dim dlgRect As NativeMethods.Rect
  526.            NativeMethods.GetWindowRect(hWnd, dlgRect)
  527.  
  528.            ' Set the custom Font (if any).
  529.            If hText <> IntPtr.Zero Then
  530.  
  531.                Me.SetFont(font:=Me.font1,
  532.                           hwnd:=hText,
  533.                           rect:=frmRect)
  534.  
  535.            End If
  536.  
  537.            ' Center the dialog window in the specified Form.
  538.            Me.CenterDialog(hwnd:=hWnd,
  539.                            dialogRect:=dlgRect,
  540.                            formRect:=frmRect)
  541.  
  542.            ' Stop the EnumThreadWndProc callback by sending False.
  543.            Return False
  544.  
  545.        End Function
  546.  
  547.        ''' <summary>
  548.        ''' Sets the font of this <see cref="CenteredMessageBox"/> window.
  549.        ''' </summary>
  550.        ''' <param name="font">The <see cref="Font"/> used to display the <see cref="CenteredMessageBox"/> text.</param>
  551.        ''' <param name="hwnd">A handle to the <see cref="CenteredMessageBox"/> window.</param>
  552.        ''' <param name="rect">A <see cref="Rectangle"/> to positionate the text.</param>
  553.        Private Sub SetFont(ByVal font As Font,
  554.                            ByVal hwnd As IntPtr,
  555.                            ByVal rect As Rectangle)
  556.  
  557.            Select Case font IsNot Nothing
  558.  
  559.                Case True
  560.                    ' Set the text position.
  561.                    NativeMethods.SetWindowPos(hWnd:=hwnd,
  562.                                               hWndInsertAfter:=IntPtr.Zero,
  563.                                               x:=65,
  564.                                               y:=35,
  565.                                               cx:=rect.Width,
  566.                                               cy:=font.Height,
  567.                                               uFlags:=NativeMethods.SetWindowPosFlags.None)
  568.  
  569.                    ' Set the font.
  570.                    NativeMethods.SendMessage(hWnd:=hwnd,
  571.                                              msg:=NativeMethods.WindowsMessages.WM_SETFONT,
  572.                                              wParam:=font.ToHfont,
  573.                                              lParam:=New IntPtr(1))
  574.  
  575.                Case Else
  576.                    ' Do Nothing.
  577.  
  578.                    ' Get the dialog font.
  579.                    ' dim fnt as Font = Font.FromHfont(NativeMethods.SendMessage(hWnd:=hwnd,
  580.                    '                                                            msg:=NativeMethods.WindowsMessages.WM_GETFONT,
  581.                    '                                                            wParam:=IntPtr.Zero,
  582.                    '                                                            lParam:=IntPtr.Zero))
  583.  
  584.            End Select
  585.  
  586.        End Sub
  587.  
  588.        ''' <summary>
  589.        ''' Centers the <see cref="CenteredMessageBox"/> dialog in the specified <see cref="Form"/>.
  590.        ''' </summary>
  591.        ''' <param name="hwnd">A handle to the <see cref="CenteredMessageBox"/> window.</param>
  592.        ''' <param name="dialogRect">The dialog <see cref="NativeMethods.Rect"/> structure.</param>
  593.        ''' <param name="formRect">The form <see cref="Rectangle"/> structure.</param>
  594.        Private Sub CenterDialog(ByVal hwnd As IntPtr,
  595.                                 ByVal dialogRect As NativeMethods.Rect,
  596.                                 ByVal formRect As Rectangle)
  597.  
  598.            ' Resize and positionate the messagebox window.
  599.            NativeMethods.MoveWindow(hwnd,
  600.                                     x:=formRect.Left + (formRect.Width - dialogRect.Right + dialogRect.Left) \ 2I,
  601.                                     y:=formRect.Top + (formRect.Height - dialogRect.Bottom + dialogRect.Top) \ 2I,
  602.                                     width:=(dialogRect.Right - dialogRect.Left),
  603.                                     height:=(dialogRect.Bottom - dialogRect.Top),
  604.                                     repaint:=True)
  605.  
  606.        End Sub
  607.  
  608. #End Region
  609.  
  610. #Region " Event Handlers "
  611.  
  612.        ''' <summary>
  613.        ''' Handles the Tick event of the TimeoutTimer control.
  614.        ''' </summary>
  615.        ''' <param name="sender">The source of the event.</param>
  616.        ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  617.        Private Sub TimeoutTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) _
  618.        Handles timeoutTimer.Tick
  619.  
  620.            NativeMethods.DestroyWindow(Me.messageBoxWindowHandle1)
  621.            Me.Dispose()
  622.  
  623.        End Sub
  624.  
  625. #End Region
  626.  
  627. #Region " IDisposable "
  628.  
  629.        ''' <summary>
  630.        ''' To detect redundant calls when disposing.
  631.        ''' </summary>
  632.        Private isDisposed As Boolean = False
  633.  
  634.        ''' <summary>
  635.        ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  636.        ''' </summary>
  637.        Public Sub Dispose() Implements IDisposable.Dispose
  638.  
  639.            Me.Dispose(isDisposing:=True)
  640.            GC.SuppressFinalize(obj:=Me)
  641.  
  642.        End Sub
  643.  
  644.        ''' <summary>
  645.        ''' Releases unmanaged and - optionally - managed resources.
  646.        ''' </summary>
  647.        ''' <param name="IsDisposing">
  648.        ''' <c>true</c> to release both managed and unmanaged resources;
  649.        ''' <c>false</c> to release only unmanaged resources.
  650.        ''' </param>
  651.        Protected Sub Dispose(ByVal isDisposing As Boolean)
  652.  
  653.            If Not Me.isDisposed Then
  654.  
  655.                If isDisposing Then
  656.  
  657.                    Me.tries = -1
  658.                    Me.ownerForm1 = Nothing
  659.  
  660.                    If Me.font1 IsNot Nothing Then
  661.                        Me.font1.Dispose()
  662.                    End If
  663.  
  664.                End If
  665.  
  666.            End If
  667.  
  668.            Me.isDisposed = True
  669.  
  670.        End Sub
  671.  
  672. #End Region
  673.  
  674.    End Class
  675.  
  676. End Namespace
  677.  
  678. #End Region
Páginas: 1 ... 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 [638] 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 ... 1254
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines