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


Tema destacado: Únete al Grupo Steam elhacker.NET


  Mostrar Mensajes
Páginas: 1 ... 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 [758] 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 ... 1254
7571  Seguridad Informática / Hacking / Re: Importante (Packet Editor, Proxy) en C# en: 20 Febrero 2014, 23:49 pm
A ver si dejas de duplicar posts, y empiezas por leer las normas del foro.

Saludos
7572  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 20 Febrero 2014, 06:06 am
Una helper class para las librerías 'SautinSoft.HtmlToRtf' y 'SautinSoft.RtfToHtml', como sus nombres indican, para convertir distintos documentos entre HTML, RTF, DOC y TXT.

La verdad es que se consiguen muy buenos resultados y tiene muchas opciones de customización, esta librería es mucho mejor que la que posteé hace unas semanas del cual también hice un ayudante.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-20-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DocumentConverter.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Example Usages "
  11.  
  12. ' ' HTML 2 RTF
  13. ' RichTextBox1.Rtf = HTMLConverter.Html2Rtf(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
  14. '                                           SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  15. '                                           DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  16. '                                           "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  17. '                                           DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  18. '                                           SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
  19.  
  20.  
  21. ' ' HTML 2 TXT
  22. ' RichTextBox1.Text = HTMLConverter.Html2Txt(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
  23. '                                            SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  24. '                                            DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  25. '                                            "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  26. '                                            DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  27. '                                            SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
  28.  
  29.  
  30. ' ' HTML 2 DOC
  31. ' Dim MSDocText As String = HTMLConverter.Html2Doc(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default),
  32. '                                                  SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  33. '                                                  DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  34. '                                                  "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  35. '                                                  DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  36. '                                                  SautinSoft.HtmlToRtf.eImageCompatible.MSWord)
  37. ' IO.File.WriteAllText("C:\DocFile.doc", MSDocText, System.Text.Encoding.Default)
  38.  
  39.  
  40. ' ' TXT 2 RTF
  41. ' RichTextBox1.Rtf = DocumentConverter.Txt2Rtf("Hello World!",
  42. '                                              SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  43. '                                              DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  44. '                                              "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  45. '                                              DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  46. '                                              SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
  47.  
  48.  
  49. ' ' TXT 2 DOC
  50. ' Dim MSDocText As String = DocumentConverter.Txt2Doc("Hello World!",
  51. '                                                     SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False,
  52. '                                                     DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst,
  53. '                                                     "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined,
  54. '                                                     DocumentConverter.PageOrientation.Auto, "Header", "Footer",
  55. '                                                     SautinSoft.HtmlToRtf.eImageCompatible.WordPad)
  56. ' IO.File.WriteAllText("C:\DocFile.doc", MSDocText, System.Text.Encoding.Default)
  57.  
  58.  
  59. ' ' RTF 2 HTML
  60. ' Dim HTMLString As String =
  61. '     DocumentConverter.Rtf2Html(IO.File.ReadAllText("C:\File.rtf"),
  62. '                                SautinSoft.RtfToHtml.eOutputFormat.XHTML_10,
  63. '                                SautinSoft.RtfToHtml.eEncoding.UTF_8,
  64. '                                True, "C:\")
  65. '
  66. ' IO.File.WriteAllText("C:\File.html", HTMLString)
  67. ' Process.Start("C:\File.html")
  68.  
  69. #End Region
  70.  
  71. #Region " Imports "
  72.  
  73. Imports SautinSoft
  74. Imports System.Reflection
  75.  
  76. #End Region
  77.  
  78. ''' <summary>
  79. ''' Performs HTML document convertions to other document formats.
  80. ''' </summary>
  81. Public Class DocumentConverter
  82.  
  83. #Region " Enumerations "
  84.  
  85.    ''' <summary>
  86.    ''' Indicates the resulting PageSize.
  87.    ''' </summary>
  88.    Public Enum PageSize
  89.        Auto
  90.        A3
  91.        A4
  92.        A5
  93.        A6
  94.        B5Iso
  95.        B5Jis
  96.        B6
  97.        Executive
  98.        Folio
  99.        Legal
  100.        Letter
  101.        Oficio2
  102.        Statement
  103.    End Enum
  104.  
  105.    ''' <summary>
  106.    ''' Indicates the resulting PageOrientation.
  107.    ''' </summary>
  108.    Public Enum PageOrientation
  109.        Auto
  110.        Landscape
  111.        Portrait
  112.    End Enum
  113.  
  114. #End Region
  115.  
  116. #Region " Private Methods "
  117.  
  118.    ''' <summary>
  119.    ''' Converts a document using 'SautinSoft.HtmlToRtf' library.
  120.    ''' </summary>
  121.    ''' <param name="Text">
  122.    ''' Indicates the text to convert.
  123.    ''' </param>
  124.    ''' <param name="OutputFormat">
  125.    ''' Indicates the output document format.
  126.    ''' </param>
  127.    ''' <param name="TextEncoding">
  128.    ''' Indicates the text encoding.
  129.    ''' </param>
  130.    ''' <param name="PreservePageBreaks">
  131.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  132.    ''' </param>
  133.    ''' <param name="PageSize">
  134.    ''' Indicates the page size.
  135.    ''' </param>
  136.    ''' <param name="Pagenumbers">
  137.    ''' Indicates the page numbers.
  138.    ''' </param>
  139.    ''' <param name="PagenumbersFormat">
  140.    ''' Indicates the page numbers format.
  141.    ''' </param>
  142.    ''' <param name="PageAlignment">
  143.    ''' Indicates the page alignment.
  144.    ''' </param>
  145.    ''' <param name="PageOrientation">
  146.    ''' Indicates the page orientation.
  147.    ''' </param>
  148.    ''' <param name="PageHeader">
  149.    ''' Indicates the page header text.
  150.    ''' </param>
  151.    ''' <param name="PageFooter">
  152.    ''' Indicates the page footer text.
  153.    ''' </param>
  154.    ''' <param name="ImageCompatibility">
  155.    ''' Indicates the image compatibility if the document contains images.
  156.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  157.    ''' Microsoft Word can show images in jpeg, png, etc.
  158.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  159.    ''' </param>
  160.    ''' <returns>System.String.</returns>
  161.    Private Shared Function HtmlToRtfConvert(ByVal [Text] As String,
  162.                                             ByVal InputFormat As HtmlToRtf.eInputFormat,
  163.                                             ByVal OutputFormat As HtmlToRtf.eOutputFormat,
  164.                                             Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  165.                                             Optional ByVal PreservePageBreaks As Boolean = False,
  166.                                             Optional ByVal PageSize As PageSize = PageSize.Auto,
  167.                                             Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  168.                                             Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  169.                                             Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  170.                                             Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  171.                                             Optional ByVal PageHeader As String = Nothing,
  172.                                             Optional ByVal PageFooter As String = Nothing,
  173.                                             Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad) As String
  174.  
  175.        ' Set the PageSize.
  176.        Dim PerformPageSize As New HtmlToRtf.CPageStyle.CPageSize()
  177.        Dim PageSizeMethod As MethodInfo = PerformPageSize.GetType().GetMethod(PageSize.ToString())
  178.  
  179.        ' Set the PageOrientation.
  180.        Dim PerformPageOrientation As New HtmlToRtf.CPageStyle.CPageOrientation
  181.        Dim PageOrientationMethod As MethodInfo = PerformPageOrientation.GetType().GetMethod(PageOrientation.ToString())
  182.  
  183.        ' Call the PageSize method.
  184.        If Not PageSizeMethod Is Nothing Then
  185.            PageSizeMethod.Invoke(PerformPageSize, Nothing)
  186.        Else
  187.            Throw New Exception(String.Format("PageSize method {0} not found.", PageSize.ToString))
  188.        End If
  189.  
  190.        ' Call the PageOrientation method.
  191.        If Not PageOrientationMethod Is Nothing Then
  192.            PageOrientationMethod.Invoke(PerformPageOrientation, Nothing)
  193.        Else
  194.            Throw New Exception(String.Format("PageOrientation method {0} not found.", PageOrientation.ToString))
  195.        End If
  196.  
  197.        ' Instance a new document converter.
  198.        Dim Converter As New HtmlToRtf
  199.  
  200.        ' Customize the conversion options.
  201.        With Converter
  202.  
  203.            .Serial = "123456789012"
  204.  
  205.            .InputFormat = InputFormat
  206.            .OutputFormat = OutputFormat
  207.            .Encoding = TextEncoding
  208.            .PreservePageBreaks = PreservePageBreaks
  209.            .ImageCompatible = ImageCompatibility
  210.            .PageAlignment = PageAlignment
  211.            .PageNumbers = Pagenumbers
  212.            .PageNumbersFormat = PagenumbersFormat
  213.            .PageStyle.PageSize = PerformPageSize
  214.            .PageStyle.PageOrientation = PerformPageOrientation
  215.            If Not String.IsNullOrEmpty(PageHeader) Then .PageStyle.PageHeader.Text(PageHeader)
  216.            If Not String.IsNullOrEmpty(PageFooter) Then .PageStyle.PageFooter.Text(PageFooter)
  217.  
  218.        End With
  219.  
  220.        ' Convert it.
  221.        Return Converter.ConvertString([Text])
  222.  
  223.    End Function
  224.  
  225.    ''' <summary>
  226.    ''' Converts a document using 'SautinSoft.RtfToHtml' library.
  227.    ''' </summary>
  228.    ''' <param name="Text">
  229.    ''' Indicates the text to convert.
  230.    ''' </param>
  231.    ''' <param name="OutputFormat">
  232.    ''' Indicates the output HTML format.
  233.    ''' </param>
  234.    ''' <param name="TextEncoding">
  235.    ''' Indicates the text encoding.
  236.    ''' </param>
  237.    ''' <param name="SaveImagesToDisk">
  238.    ''' If set to <c>true</c>, converted images are saved to a directory on hard drive.
  239.    ''' </param>
  240.    ''' <param name="ImageFolder">
  241.    ''' If 'SaveImagesToDisk' parameter is set to 'True', indicates the image directory to save the images.
  242.    ''' The directory must exist.
  243.    ''' </param>
  244.    ''' <returns>System.String.</returns>
  245.    Private Shared Function RtfToHtmlConvert(ByVal [Text] As String,
  246.                                             Optional ByVal OutputFormat As RtfToHtml.eOutputFormat = RtfToHtml.eOutputFormat.XHTML_10,
  247.                                             Optional ByVal TextEncoding As RtfToHtml.eEncoding = RtfToHtml.eEncoding.UTF_8,
  248.                                             Optional ByVal SaveImagesToDisk As Boolean = False,
  249.                                             Optional ByVal ImageFolder As String = "C:\") As String
  250.  
  251.  
  252.        ' Instance a new document converter.
  253.        Dim Converter As New RtfToHtml
  254.  
  255.        ' Customize the conversion options.
  256.        With Converter
  257.  
  258.            .Serial = "123456789012"
  259.  
  260.            .OutputFormat = OutputFormat
  261.            .Encoding = TextEncoding
  262.            .ImageStyle.IncludeImageInHtml = Not SaveImagesToDisk
  263.            .ImageStyle.ImageFolder = ImageFolder ' This folder must exist to save the converted images.
  264.            .ImageStyle.ImageSubFolder = "Pictures" ' This subfolder will be created by the component to save the images.
  265.            .ImageStyle.ImageFileName = "picture" ' Pattern name for converted images. (Ex: 'Picture1.png')
  266.  
  267.        End With
  268.  
  269.        ' Convert it.
  270.        Return Converter.ConvertString([Text])
  271.  
  272.    End Function
  273.  
  274. #End Region
  275.  
  276. #Region " Public Methods "
  277.  
  278.    ''' <summary>
  279.    ''' Converts HTML text to DOC (Microsoft Word).
  280.    ''' </summary>
  281.    ''' <param name="HtmlText">
  282.    ''' Indicates the HTML text to convert.
  283.    ''' </param>
  284.    ''' <param name="TextEncoding">
  285.    ''' Indicates the text encoding.
  286.    ''' </param>
  287.    ''' <param name="PreservePageBreaks">
  288.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  289.    ''' </param>
  290.    ''' <param name="PageSize">
  291.    ''' Indicates the page size.
  292.    ''' </param>
  293.    ''' <param name="Pagenumbers">
  294.    ''' Indicates the page numbers.
  295.    ''' </param>
  296.    ''' <param name="PagenumbersFormat">
  297.    ''' Indicates the page numbers format.
  298.    ''' </param>
  299.    ''' <param name="PageAlignment">
  300.    ''' Indicates the page alignment.
  301.    ''' </param>
  302.    ''' <param name="PageOrientation">
  303.    ''' Indicates the page orientation.
  304.    ''' </param>
  305.    ''' <param name="PageHeader">
  306.    ''' Indicates the page header text.
  307.    ''' </param>
  308.    ''' <param name="PageFooter">
  309.    ''' Indicates the page footer text.
  310.    ''' </param>
  311.    ''' <param name="ImageCompatibility">
  312.    ''' Indicates the image compatibility if the document contains images.
  313.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  314.    ''' Microsoft Word can show images in jpeg, png, etc.
  315.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  316.    ''' </param>
  317.    ''' <returns>System.String.</returns>
  318.    Public Shared Function Html2Doc(ByVal HtmlText As String,
  319.                                    Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  320.                                    Optional ByVal PreservePageBreaks As Boolean = False,
  321.                                    Optional ByVal PageSize As PageSize = PageSize.Auto,
  322.                                    Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  323.                                    Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  324.                                    Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  325.                                    Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  326.                                    Optional ByVal PageHeader As String = Nothing,
  327.                                    Optional ByVal PageFooter As String = Nothing,
  328.                                    Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  329.                                    ) As String
  330.  
  331.        Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.Doc, TextEncoding,
  332.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  333.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  334.  
  335.    End Function
  336.  
  337.    ''' <summary>
  338.    ''' Converts HTML text to RTF (Rich Text).
  339.    ''' </summary>
  340.    ''' <param name="HtmlText">
  341.    ''' Indicates the HTML text to convert.
  342.    ''' </param>
  343.    ''' <param name="TextEncoding">
  344.    ''' Indicates the text encoding.
  345.    ''' </param>
  346.    ''' <param name="PreservePageBreaks">
  347.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  348.    ''' </param>
  349.    ''' <param name="PageSize">
  350.    ''' Indicates the page size.
  351.    ''' </param>
  352.    ''' <param name="Pagenumbers">
  353.    ''' Indicates the page numbers.
  354.    ''' </param>
  355.    ''' <param name="PagenumbersFormat">
  356.    ''' Indicates the page numbers format.
  357.    ''' </param>
  358.    ''' <param name="PageAlignment">
  359.    ''' Indicates the page alignment.
  360.    ''' </param>
  361.    ''' <param name="PageOrientation">
  362.    ''' Indicates the page orientation.
  363.    ''' </param>
  364.    ''' <param name="PageHeader">
  365.    ''' Indicates the page header text.
  366.    ''' </param>
  367.    ''' <param name="PageFooter">
  368.    ''' Indicates the page footer text.
  369.    ''' </param>
  370.    ''' <param name="ImageCompatibility">
  371.    ''' Indicates the image compatibility if the document contains images.
  372.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  373.    ''' Microsoft Word can show images in jpeg, png, etc.
  374.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  375.    ''' </param>
  376.    ''' <returns>System.String.</returns>
  377.    Public Shared Function Html2Rtf(ByVal HtmlText As String,
  378.                                    Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  379.                                    Optional ByVal PreservePageBreaks As Boolean = False,
  380.                                    Optional ByVal PageSize As PageSize = PageSize.Auto,
  381.                                    Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  382.                                    Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  383.                                    Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  384.                                    Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  385.                                    Optional ByVal PageHeader As String = Nothing,
  386.                                    Optional ByVal PageFooter As String = Nothing,
  387.                                    Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  388.                                    ) As String
  389.  
  390.        Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.Rtf, TextEncoding,
  391.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  392.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  393.  
  394.    End Function
  395.  
  396.    ''' <summary>
  397.    ''' Converts HTML text to TXT (Plain Text).
  398.    ''' </summary>
  399.    ''' <param name="HtmlText">
  400.    ''' Indicates the HTML text to convert.
  401.    ''' </param>
  402.    ''' <param name="TextEncoding">
  403.    ''' Indicates the text encoding.
  404.    ''' </param>
  405.    ''' <param name="PreservePageBreaks">
  406.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  407.    ''' </param>
  408.    ''' <param name="PageSize">
  409.    ''' Indicates the page size.
  410.    ''' </param>
  411.    ''' <param name="Pagenumbers">
  412.    ''' Indicates the page numbers.
  413.    ''' </param>
  414.    ''' <param name="PagenumbersFormat">
  415.    ''' Indicates the page numbers format.
  416.    ''' </param>
  417.    ''' <param name="PageAlignment">
  418.    ''' Indicates the page alignment.
  419.    ''' </param>
  420.    ''' <param name="PageOrientation">
  421.    ''' Indicates the page orientation.
  422.    ''' </param>
  423.    ''' <param name="PageHeader">
  424.    ''' Indicates the page header text.
  425.    ''' </param>
  426.    ''' <param name="PageFooter">
  427.    ''' Indicates the page footer text.
  428.    ''' </param>
  429.    ''' <param name="ImageCompatibility">
  430.    ''' Indicates the image compatibility if the document contains images.
  431.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  432.    ''' Microsoft Word can show images in jpeg, png, etc.
  433.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  434.    ''' </param>
  435.    ''' <returns>System.String.</returns>
  436.    Public Shared Function Html2Txt(ByVal HtmlText As String,
  437.                                    Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  438.                                    Optional ByVal PreservePageBreaks As Boolean = False,
  439.                                    Optional ByVal PageSize As PageSize = PageSize.Auto,
  440.                                    Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  441.                                    Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  442.                                    Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  443.                                    Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  444.                                    Optional ByVal PageHeader As String = Nothing,
  445.                                    Optional ByVal PageFooter As String = Nothing,
  446.                                    Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  447.                                    ) As String
  448.  
  449.        Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.TextAnsi, TextEncoding,
  450.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  451.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  452.  
  453.    End Function
  454.  
  455.    ''' <summary>
  456.    ''' Converts TXT to DOC (Microsoft Word).
  457.    ''' </summary>
  458.    ''' <param name="Text">
  459.    ''' Indicates the plain text to convert.
  460.    ''' </param>
  461.    ''' <param name="TextEncoding">
  462.    ''' Indicates the text encoding.
  463.    ''' </param>
  464.    ''' <param name="PreservePageBreaks">
  465.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  466.    ''' </param>
  467.    ''' <param name="PageSize">
  468.    ''' Indicates the page size.
  469.    ''' </param>
  470.    ''' <param name="Pagenumbers">
  471.    ''' Indicates the page numbers.
  472.    ''' </param>
  473.    ''' <param name="PagenumbersFormat">
  474.    ''' Indicates the page numbers format.
  475.    ''' </param>
  476.    ''' <param name="PageAlignment">
  477.    ''' Indicates the page alignment.
  478.    ''' </param>
  479.    ''' <param name="PageOrientation">
  480.    ''' Indicates the page orientation.
  481.    ''' </param>
  482.    ''' <param name="PageHeader">
  483.    ''' Indicates the page header text.
  484.    ''' </param>
  485.    ''' <param name="PageFooter">
  486.    ''' Indicates the page footer text.
  487.    ''' </param>
  488.    ''' <param name="ImageCompatibility">
  489.    ''' Indicates the image compatibility if the document contains images.
  490.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  491.    ''' Microsoft Word can show images in jpeg, png, etc.
  492.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  493.    ''' </param>
  494.    ''' <returns>System.String.</returns>
  495.    Public Shared Function Txt2Doc(ByVal [Text] As String,
  496.                                   Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  497.                                   Optional ByVal PreservePageBreaks As Boolean = False,
  498.                                   Optional ByVal PageSize As PageSize = PageSize.Auto,
  499.                                   Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  500.                                   Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  501.                                   Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  502.                                   Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  503.                                   Optional ByVal PageHeader As String = Nothing,
  504.                                   Optional ByVal PageFooter As String = Nothing,
  505.                                   Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  506.                                   ) As String
  507.  
  508.        Return HtmlToRtfConvert([Text], HtmlToRtf.eInputFormat.Text, HtmlToRtf.eOutputFormat.Doc, TextEncoding,
  509.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  510.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  511.  
  512.    End Function
  513.  
  514.    ''' <summary>
  515.    ''' Converts TXT to RTF (Rich Text).
  516.    ''' </summary>
  517.    ''' <param name="Text">
  518.    ''' Indicates the plain text to convert.
  519.    ''' </param>
  520.    ''' <param name="TextEncoding">
  521.    ''' Indicates the text encoding.
  522.    ''' </param>
  523.    ''' <param name="PreservePageBreaks">
  524.    ''' If set to <c>true</c> page breaks are preserved on the conversion.
  525.    ''' </param>
  526.    ''' <param name="PageSize">
  527.    ''' Indicates the page size.
  528.    ''' </param>
  529.    ''' <param name="Pagenumbers">
  530.    ''' Indicates the page numbers.
  531.    ''' </param>
  532.    ''' <param name="PagenumbersFormat">
  533.    ''' Indicates the page numbers format.
  534.    ''' </param>
  535.    ''' <param name="PageAlignment">
  536.    ''' Indicates the page alignment.
  537.    ''' </param>
  538.    ''' <param name="PageOrientation">
  539.    ''' Indicates the page orientation.
  540.    ''' </param>
  541.    ''' <param name="PageHeader">
  542.    ''' Indicates the page header text.
  543.    ''' </param>
  544.    ''' <param name="PageFooter">
  545.    ''' Indicates the page footer text.
  546.    ''' </param>
  547.    ''' <param name="ImageCompatibility">
  548.    ''' Indicates the image compatibility if the document contains images.
  549.    ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images.
  550.    ''' Microsoft Word can show images in jpeg, png, etc.
  551.    ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF.
  552.    ''' </param>
  553.    ''' <returns>System.String.</returns>
  554.    Public Shared Function Txt2Rtf(ByVal [Text] As String,
  555.                                   Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect,
  556.                                   Optional ByVal PreservePageBreaks As Boolean = False,
  557.                                   Optional ByVal PageSize As PageSize = PageSize.Auto,
  558.                                   Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst,
  559.                                   Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}",
  560.                                   Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined,
  561.                                   Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto,
  562.                                   Optional ByVal PageHeader As String = Nothing,
  563.                                   Optional ByVal PageFooter As String = Nothing,
  564.                                   Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad
  565.                                   ) As String
  566.  
  567.        Return HtmlToRtfConvert([Text], HtmlToRtf.eInputFormat.Text, HtmlToRtf.eOutputFormat.Rtf, TextEncoding,
  568.                       PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat,
  569.                       PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility)
  570.  
  571.    End Function
  572.  
  573.    ''' <summary>
  574.    ''' Converts RtF to HtML.
  575.    ''' </summary>
  576.    ''' <param name="RtfText">
  577.    ''' Indicates the rich text to convert.
  578.    ''' </param>
  579.    ''' <param name="OutputFormat">
  580.    ''' Indicates the output HTML format.
  581.    ''' </param>
  582.    ''' <param name="TextEncoding">
  583.    ''' Indicates the text encoding.
  584.    ''' </param>
  585.    ''' <param name="SaveImagesToDisk">
  586.    ''' If set to <c>true</c>, converted images are saved to a directory on hard drive.
  587.    ''' </param>
  588.    ''' <param name="ImageFolder">
  589.    ''' If 'SaveImagesToDisk' parameter is set to 'True', indicates the image directory to save the images.
  590.    ''' The directory must exist.
  591.    ''' </param>
  592.    ''' <returns>System.String.</returns>
  593.    Public Shared Function Rtf2Html(ByVal RtfText As String,
  594.                                    Optional ByVal OutputFormat As RtfToHtml.eOutputFormat = RtfToHtml.eOutputFormat.XHTML_10,
  595.                                    Optional ByVal TextEncoding As RtfToHtml.eEncoding = RtfToHtml.eEncoding.UTF_8,
  596.                                    Optional ByVal SaveImagesToDisk As Boolean = False,
  597.                                    Optional ByVal ImageFolder As String = "C:\") As String
  598.  
  599.        Return RtfToHtmlConvert(RtFText, OutputFormat, TextEncoding, SaveImagesToDisk, ImageFolder)
  600.  
  601.    End Function
  602.  
  603. #End Region
  604.  
  605. End Class
7573  Informática / Software / Re: Duda sobre la existencia de un programa en: 19 Febrero 2014, 22:34 pm
No creo que exista un software dedicado a una tarea tan "singular", pero de todas formas no es dificil conseguirlo escribiendo un Script/Programa, partiendo cada linea de texto usando como delimitador el caracter de 'espacio'.

Slaudos!
7574  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 19 Febrero 2014, 21:54 pm
         [RichTextBox] Colorize Words

         Busca coincidencias de texto y las colorea.


Código
  1.    ' Colorize Words
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    ' ColorizeWord(RichTextBox1, "Hello", True,
  7.    '              Color.Red, Color.Black,
  8.    '              New Font(RichTextBox1.Font.FontFamily, RichTextBox1.Font.Size, FontStyle.Italic))
  9.    '
  10.    ' ColorizeWords(RichTextBox1, {"Hello", "[0-9]"}, IgnoreCase:=False,
  11.    '               ForeColor:=Color.Red, BackColor:=Nothing, Font:=Nothing)
  12.  
  13.    ''' <summary>
  14.    ''' Find a word on a RichTextBox and colorizes each match.
  15.    ''' </summary>
  16.    ''' <param name="RichTextBox">Indicates the RichTextBox.</param>
  17.    ''' <param name="Word">Indicates the word to colorize.</param>
  18.    ''' <param name="IgnoreCase">Indicates the ignore case.</param>
  19.    ''' <param name="ForeColor">Indicates the text color.</param>
  20.    ''' <param name="BackColor">Indicates the background color.</param>
  21.    ''' <param name="Font">Indicates the text font.</param>
  22.    ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
  23.    Private Function ColorizeWord(ByVal [RichTextBox] As RichTextBox,
  24.                                  ByVal Word As String,
  25.                                  Optional ByVal IgnoreCase As Boolean = False,
  26.                                  Optional ByVal ForeColor As Color = Nothing,
  27.                                  Optional ByVal BackColor As Color = Nothing,
  28.                                  Optional ByVal [Font] As Font = Nothing) As Boolean
  29.  
  30.        ' Find all the word matches.
  31.        Dim Matches As System.Text.RegularExpressions.MatchCollection =
  32.            System.Text.RegularExpressions.Regex.Matches([RichTextBox].Text, Word,
  33.                                                         If(IgnoreCase,
  34.                                                            System.Text.RegularExpressions.RegexOptions.IgnoreCase,
  35.                                                            System.Text.RegularExpressions.RegexOptions.None))
  36.  
  37.        ' If no matches then return.
  38.        If Not Matches.Count <> 0 Then
  39.            Return False
  40.        End If
  41.  
  42.        ' Set the passed Parameter values.
  43.        If ForeColor.Equals(Nothing) Then ForeColor = [RichTextBox].ForeColor
  44.        If BackColor.Equals(Nothing) Then BackColor = [RichTextBox].BackColor
  45.        If [Font] Is Nothing Then [Font] = [RichTextBox].Font
  46.  
  47.        ' Store the current caret position to restore it at the end.
  48.        Dim CaretPosition As Integer = [RichTextBox].SelectionStart
  49.  
  50.        ' Suspend the control layout to work quicklly.
  51.        [RichTextBox].SuspendLayout()
  52.  
  53.        ' Colorize each match.
  54.        For Each Match As System.Text.RegularExpressions.Match In Matches
  55.  
  56.            [RichTextBox].Select(Match.Index, Match.Length)
  57.            [RichTextBox].SelectionColor = ForeColor
  58.            [RichTextBox].SelectionBackColor = BackColor
  59.            [RichTextBox].SelectionFont = [Font]
  60.  
  61.        Next Match
  62.  
  63.        ' Restore the caret position.
  64.        [RichTextBox].Select(CaretPosition, 0)
  65.  
  66.        ' Restore the control layout.
  67.        [RichTextBox].ResumeLayout()
  68.  
  69.        ' Return successfully
  70.        Return True
  71.  
  72.    End Function
  73.  
  74.    ''' <summary>
  75.    ''' Find multiple words on a RichTextBox and colorizes each match.
  76.    ''' </summary>
  77.    ''' <param name="RichTextBox">Indicates the RichTextBox.</param>
  78.    ''' <param name="Words">Indicates the words to colorize.</param>
  79.    ''' <param name="IgnoreCase">Indicates the ignore case.</param>
  80.    ''' <param name="ForeColor">Indicates the text color.</param>
  81.    ''' <param name="BackColor">Indicates the background color.</param>
  82.    ''' <param name="Font">Indicates the text font.</param>
  83.    ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns>
  84.    Private Function ColorizeWords(ByVal [RichTextBox] As RichTextBox,
  85.                                   ByVal Words As String(),
  86.                                   Optional ByVal IgnoreCase As Boolean = False,
  87.                                   Optional ByVal ForeColor As Color = Nothing,
  88.                                   Optional ByVal BackColor As Color = Nothing,
  89.                                   Optional ByVal [Font] As Font = Nothing) As Boolean
  90.  
  91.        Dim Success As Boolean = False
  92.  
  93.        For Each Word As String In Words
  94.            Success += ColorizeWord([RichTextBox], Word, IgnoreCase, ForeColor, BackColor, [Font])
  95.        Next Word
  96.  
  97.        Return Success
  98.  
  99.    End Function



[ListView] Remove Duplicates

Elimina Items duplicados de un Listview, comparando un índice de subitem específico.

Código
  1.    ' Remove ListView Duplicates
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' Dim Items As ListView.ListViewItemCollection = New ListView.ListViewItemCollection(ListView1)
  6.    ' RemoveListViewDuplicates(Items, 0)    
  7.    '
  8.    ''' <summary>
  9.    ''' Removes duplicated items from a Listview.
  10.    ''' </summary>
  11.    ''' <param name="Items">
  12.    ''' Indicates the items collection.
  13.    ''' </param>
  14.    ''' <param name="SubitemCompare">
  15.    ''' Indicates the subitem column to compare duplicates.
  16.    ''' </param>
  17.    Private Sub RemoveListViewDuplicates(ByVal Items As ListView.ListViewItemCollection,
  18.                                         ByVal SubitemCompare As Integer)
  19.  
  20.        ' Suspend the layout on the Control that owns the Items collection.
  21.        Items.Item(0).ListView.SuspendLayout()
  22.  
  23.        ' Get the duplicated Items.
  24.        Dim Duplicates As ListViewItem() =
  25.            Items.Cast(Of ListViewItem)().
  26.            GroupBy(Function(Item As ListViewItem) Item.SubItems(SubitemCompare).Text).
  27.            Where(Function(g As IGrouping(Of String, ListViewItem)) g.Count <> 1).
  28.            SelectMany(Function(g As IGrouping(Of String, ListViewItem)) g).
  29.            Skip(1).
  30.            ToArray()
  31.  
  32.        ' Delete the duplicated Items.
  33.        For Each Item As ListViewItem In Duplicates
  34.            Items.Remove(Item)
  35.        Next Item
  36.  
  37.        ' Resume the layout on the Control that owns the Items collection.
  38.        Items.Item(0).ListView.ResumeLayout()
  39.  
  40.        Duplicates = Nothing
  41.  
  42.    End Sub
  43.  



Formatea un dispositivo

Código
  1.    ' Format Drive
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' FormatDrive("Z")
  6.    ' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False))
  7.  
  8.    ''' <summary>
  9.    ''' Indicates the possible HardDisk filesystem's for Windows OS.
  10.    ''' </summary>
  11.    Public Enum DriveFileSystem As Integer
  12.  
  13.        ' NOTE:
  14.        ' *****
  15.        ' The numeric values just indicates the max harddisk volume-label character-length for each filesystem.
  16.  
  17.        ''' <summary>
  18.        ''' NTFS FileSystem.
  19.        ''' </summary>
  20.        NTFS = 32
  21.  
  22.        ''' <summary>
  23.        ''' FAT16 FileSystem.
  24.        ''' </summary>
  25.        FAT16 = 11
  26.  
  27.        ''' <summary>
  28.        ''' FAT32 FileSystem.
  29.        ''' </summary>
  30.        FAT32 = FAT16
  31.  
  32.    End Enum
  33.  
  34.    ''' <summary>
  35.    ''' Formats a drive.
  36.    ''' For more info see here:
  37.    ''' http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx
  38.    ''' </summary>
  39.    ''' <param name="DriveLetter">
  40.    ''' Indicates the drive letter to format.
  41.    ''' </param>
  42.    ''' <param name="FileSystem">
  43.    ''' Indicates the filesystem format to use for this volume.
  44.    ''' The default is "NTFS".
  45.    ''' </param>
  46.    ''' <param name="QuickFormat">
  47.    ''' If set to <c>true</c>, formats the volume with a quick format by removing files from the disk
  48.    ''' without scanning the disk for bad sectors.
  49.    ''' Use this option only if the disk has been previously formatted,
  50.    ''' and you know that the disk is not damaged.
  51.    ''' The default is <c>true</c>.
  52.    ''' </param>
  53.    ''' <param name="ClusterSize">
  54.    ''' Disk allocation unit size—cluster size.
  55.    ''' All of the filesystems organizes the hard disk based on cluster size,
  56.    ''' which represents the smallest amount of disk space that can be allocated to hold a file.
  57.    ''' The smaller the cluster size you use, the more efficiently your disk stores information.
  58.    ''' If no cluster size is specified during format, Windows picks defaults based on the size of the volume.
  59.    ''' These defaults have been selected to reduce the amount of space lost and to reduce fragmentation.
  60.    ''' For general use, the default settings are strongly recommended.
  61.    ''' </param>
  62.    ''' <param name="VolumeLabel">
  63.    ''' Indicates the Label to use for the new volume.
  64.    ''' The volume label can contain up to 11 characters for FAT16 and FAT32 volumes,
  65.    ''' and up to 32 characters for NTFS filesystem volumes.
  66.    ''' </param>
  67.    ''' <param name="EnableCompression">Not implemented.</param>
  68.    ''' <returns>
  69.    ''' 0  = Success.
  70.    ''' 1  = Unsupported file system.
  71.    ''' 2  = Incompatible media in drive.
  72.    ''' 3  = Access denied.
  73.    ''' 4  = Call canceled.
  74.    ''' 5  = Call cancellation request too late.
  75.    ''' 6  = Volume write protected.
  76.    ''' 7  = Volume lock failed.
  77.    ''' 8  = Unable to quick format.
  78.    ''' 9  = Input/Output (I/O) error.
  79.    ''' 10 = Invalid volume label.
  80.    ''' 11 = No media in drive.
  81.    ''' 12 = Volume is too small.
  82.    ''' 13 = Volume is too large.
  83.    ''' 14 = Volume is not mounted.
  84.    ''' 15 = Cluster size is too small.
  85.    ''' 16 = Cluster size is too large.
  86.    ''' 17 = Cluster size is beyond 32 bits.
  87.    ''' 18 = Unknown error.
  88.    ''' </returns>
  89.    Public Function FormatDrive(ByVal DriveLetter As Char,
  90.                                Optional ByVal FileSystem As DriveFileSystem = DriveFileSystem.NTFS,
  91.                                Optional ByVal QuickFormat As Boolean = True,
  92.                                Optional ByVal ClusterSize As Integer = Nothing,
  93.                                Optional ByVal VolumeLabel As String = Nothing,
  94.                                Optional ByVal EnableCompression As Boolean = False) As Integer
  95.  
  96.        ' Volume-label error check.
  97.        If Not String.IsNullOrEmpty(VolumeLabel) Then
  98.  
  99.            If VolumeLabel.Length > FileSystem Then
  100.                Throw New Exception(String.Format("Volume label for '{0}' filesystem can't be larger than '{1}' characters.",
  101.                                                  FileSystem.ToString, CStr(FileSystem)))
  102.            End If
  103.  
  104.        End If
  105.  
  106.        Dim Query As String = String.Format("select * from Win32_Volume WHERE DriveLetter = '{0}:'",
  107.                                            Convert.ToString(DriveLetter))
  108.  
  109.        Using WMI As New ManagementObjectSearcher(Query)
  110.  
  111.            Return CInt(WMI.[Get].Cast(Of ManagementObject).First.
  112.                        InvokeMethod("Format",
  113.                                     New Object() {FileSystem, QuickFormat, ClusterSize, VolumeLabel, EnableCompression}))
  114.  
  115.        End Using
  116.  
  117.        Return 18 ' Unknown error.
  118.  
  119.    End Function
7575  Programación / Java / Re: hacer compareTo con vector de char (para ordenar nombres) en: 19 Febrero 2014, 05:37 am
Porfavor, usa las etiquetas de código... respeta las normas del foro.

PD: Sobre el código, no se Java.

Saludos!
7576  Programación / Programación General / Re: Batch y Registros en: 18 Febrero 2014, 20:59 pm
El caracter "%" es un símbolo reservado por el sistema (para las %variables%), pero, además de esto, el espacio escrito en la ruta del regedit (%20) entra en conflicto con la variable especial "%2" de Batch, por eso te da error.

Para corregirlo, encierra el string y escapa el caracter conflictivo (duplicándolo):

Código
  1. @Echo OFF
  2.  
  3. Set "Output=%HomeDrive%\Registros\Cliente.reg"
  4. Set "Key=HKCU\Software\SimonTatham\PuTTY\Sessions\CIA%%20-%%20Cliente"
  5.  
  6. Reg Export "%Key%" "%Output%"
  7.  
  8. Pause&Exit

Saludos
7577  Programación / .NET (C#, VB.NET, ASP) / Re: Vb.net simular presion tecla INSERT en: 18 Febrero 2014, 08:31 am
No entiendo cual será el problema

El método SendKeys.Send envía las pulsaciones del teclado a la ventana activa, ¿has tenido eso en cuenta?.

Muestra el código restante, es imposible poder ayudarte sin ver donde cometes el fallo (si hubiera alguno) o como estás usándolo.





De todas formas una alternativa para esta tarea que requieres quizás podría ser usando el método SendInput

He estado haciendo mi implementación de SendInput, todavía está muy verde, no lo he acabado, falta documentación por añadir y mucho código que escribir, y quizás bugs que corregir, pero para lo que tu precisas puedes testear este código.

Modo de empleo:
Código
  1.    Private Sub Test() Handles Button1.Click
  2.  
  3.        AppActivate(Process.GetProcessesByName("notepad").First.Id)
  4.        Dim Result As Integer = SendInputs.SendKeys(Keys.Insert,  BlockInput:=False)
  5.  
  6.        ' Dim Result2 As Integer = SendInputs.SendKey(Convert.ToChar(Keys.Enter))
  7.        ' Dim Result2 As Integer = SendInputs.SendKey("x"c)
  8.  
  9. #If DEBUG Then
  10.        MessageBox.Show(String.Format("Successfull events: {0}", CStr(Result)))
  11. #End If
  12.  
  13.    End Sub

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-17-2014
  4. ' ***********************************************************************
  5. ' <copyright file="SendInputs.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Imports "
  11.  
  12. Imports System.Runtime.InteropServices
  13. Imports System.ComponentModel
  14.  
  15. #End Region
  16.  
  17. ''' <summary>
  18. '''
  19. ''' </summary>
  20. Public Class SendInputs
  21.  
  22. #Region " P/Invoke "
  23.  
  24.    Friend Class NativeMethods
  25.  
  26. #Region " Methods "
  27.  
  28.        ''' <summary>
  29.        ''' Blocks keyboard and mouse input events from reaching applications.
  30.        ''' For more info see here:
  31.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646290%28v=vs.85%29.aspx
  32.        ''' </summary>
  33.        ''' <param name="fBlockIt">
  34.        ''' The function's purpose.
  35.        ''' If this parameter is 'TRUE', keyboard and mouse input events are blocked.
  36.        ''' If this parameter is 'FALSE', keyboard and mouse events are unblocked.
  37.        ''' </param>
  38.        ''' <returns>
  39.        ''' If the function succeeds, the return value is nonzero.
  40.        ''' If input is already blocked, the return value is zero.
  41.        ''' </returns>
  42.        ''' <remarks>
  43.        ''' Note that only the thread that blocked input can successfully unblock input.
  44.        ''' </remarks>
  45.        <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall,
  46.        SetLastError:=True)>
  47.        Friend Shared Function BlockInput(
  48.               ByVal fBlockIt As Boolean
  49.        ) As Integer
  50.        End Function
  51.  
  52.        ''' <summary>
  53.        ''' Synthesizes keystrokes, mouse motions, and button clicks.
  54.        ''' For more info see here:
  55.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310%28v=vs.85%29.aspx
  56.        ''' </summary>
  57.        ''' <param name="nInputs">
  58.        ''' Indicates the number of structures in the pInputs array.
  59.        ''' </param>
  60.        ''' <param name="pInputs">
  61.        ''' Indicates an Array of 'INPUT' structures.
  62.        ''' Each structure represents an event to be inserted into the keyboard or mouse input stream.
  63.        ''' </param>
  64.        ''' <param name="cbSize">
  65.        ''' The size, in bytes, of an 'INPUT' structure.
  66.        ''' If 'cbSize' is not the size of an 'INPUT' structure, the function fails.
  67.        ''' </param>
  68.        ''' <returns>
  69.        ''' The function returns the number of events that it successfully
  70.        ''' inserted into the keyboard or mouse input stream.
  71.        ''' If the function returns zero, the input was already blocked by another thread.
  72.        ''' </returns>
  73.        <DllImport("user32.dll", SetLastError:=True)>
  74.        Friend Shared Function SendInput(
  75.               ByVal nInputs As Integer,
  76.               <MarshalAs(UnmanagedType.LPArray), [In]> ByVal pInputs As INPUT(),
  77.               ByVal cbSize As Integer
  78.        ) As Integer
  79.        End Function
  80.  
  81. #End Region
  82.  
  83. #Region " Enumerations "
  84.  
  85.        ''' <summary>
  86.        ''' VirtualKey codes.
  87.        ''' </summary>
  88.        Friend Enum VirtualKeys As Short
  89.  
  90.            ''' <summary>
  91.            ''' The Shift key.
  92.            ''' VK_SHIFT
  93.            ''' </summary>
  94.            SHIFT = &H10S
  95.  
  96.            ''' <summary>
  97.            ''' The DEL key.
  98.            ''' VK_DELETE
  99.            ''' </summary>
  100.            DELETE = 46S
  101.  
  102.            ''' <summary>
  103.            ''' The ENTER key.
  104.            ''' VK_RETURN
  105.            ''' </summary>
  106.            [RETURN] = 13S
  107.  
  108.        End Enum
  109.  
  110.        ''' <summary>
  111.        ''' The type of the input event.
  112.        ''' For more info see here:
  113.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
  114.        ''' </summary>
  115.        <Description("Enumeration used for 'type' parameter of 'INPUT' structure")>
  116.        Friend Enum InputType As Integer
  117.  
  118.            ''' <summary>
  119.            ''' The event is a mouse event.
  120.            ''' Use the mi structure of the union.
  121.            ''' </summary>
  122.            Mouse = 0
  123.  
  124.            ''' <summary>
  125.            ''' The event is a keyboard event.
  126.            ''' Use the ki structure of the union.
  127.            ''' </summary>
  128.            Keyboard = 1
  129.  
  130.            ''' <summary>
  131.            ''' The event is a hardware event.
  132.            ''' Use the hi structure of the union.
  133.            ''' </summary>
  134.            Hardware = 2
  135.  
  136.        End Enum
  137.  
  138.        ''' <summary>
  139.        ''' Specifies various aspects of a keystroke.
  140.        ''' This member can be certain combinations of the following values.
  141.        ''' For more info see here:
  142.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
  143.        ''' </summary>
  144.        <Description("Enumeration used for 'dwFlags' parameter of 'KEYBDINPUT ' structure")>
  145.        <Flags>
  146.        Friend Enum KeyboardInput_Flags As Integer
  147.  
  148.            ''' <summary>
  149.            ''' If specified, the scan code was preceded by a prefix byte that has the value '0xE0' (224).
  150.            ''' </summary>
  151.            ExtendedKey = &H1
  152.  
  153.            ''' <summary>
  154.            ''' If specified, the key is being pressed.
  155.            ''' </summary>
  156.            KeyDown = &H0
  157.  
  158.            ''' <summary>
  159.            ''' If specified, the key is being released.
  160.            ''' If not specified, the key is being pressed.
  161.            ''' </summary>
  162.            KeyUp = &H2
  163.  
  164.            ''' <summary>
  165.            ''' If specified, 'wScan' identifies the key and 'wVk' is ignored.
  166.            ''' </summary>
  167.            ScanCode = &H8
  168.  
  169.            ''' <summary>
  170.            ''' If specified, the system synthesizes a 'VK_PACKET' keystroke.
  171.            ''' The 'wVk' parameter must be '0'.
  172.            ''' This flag can only be combined with the 'KEYEVENTF_KEYUP' flag.
  173.            ''' </summary>
  174.            Unicode = &H4
  175.  
  176.        End Enum
  177.  
  178. #End Region
  179.  
  180. #Region " Structures "
  181.  
  182.        ''' <summary>
  183.        ''' Used by 'SendInput' function
  184.        ''' to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks.
  185.        ''' For more info see here:
  186.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
  187.        ''' </summary>
  188.        <Description("Structure used for 'INPUT' parameter of 'SendInput' API method")>
  189.        <StructLayout(LayoutKind.Explicit)>
  190.        Friend Structure INPUT
  191.  
  192.            ' ******
  193.            '  NOTE
  194.            ' ******
  195.            ' Field offset for 32 bit machine: 4
  196.            ' Field offset for 64 bit machine: 8
  197.  
  198.            ''' <summary>
  199.            ''' The type of the input event.
  200.            ''' </summary>
  201.            <FieldOffset(0)>
  202.            Public type As InputType
  203.  
  204.            ''' <summary>
  205.            ''' The information about a simulated mouse event.
  206.            ''' </summary>
  207.            <FieldOffset(8)>
  208.            Public mi As MOUSEINPUT
  209.  
  210.            ''' <summary>
  211.            ''' The information about a simulated keyboard event.
  212.            ''' </summary>
  213.            <FieldOffset(8)>
  214.            Public ki As KEYBDINPUT
  215.  
  216.            ''' <summary>
  217.            ''' The information about a simulated hardware event.
  218.            ''' </summary>
  219.            <FieldOffset(8)>
  220.            Public hi As HARDWAREINPUT
  221.  
  222.        End Structure
  223.  
  224.        ''' <summary>
  225.        ''' Contains information about a simulated mouse event.
  226.        ''' For more info see here:
  227.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx
  228.        ''' </summary>
  229.        <Description("Structure used for 'mi' parameter of 'INPUT' structure")>
  230.        Friend Structure MOUSEINPUT
  231.  
  232.            ''' <summary>
  233.            '''
  234.            ''' </summary>
  235.            Public dx As Integer
  236.  
  237.            ''' <summary>
  238.            '''
  239.            ''' </summary>
  240.            Public dy As Integer
  241.  
  242.            ''' <summary>
  243.            '''
  244.            ''' </summary>
  245.            Public mouseData As Integer
  246.  
  247.            ''' <summary>
  248.            '''
  249.            ''' </summary>
  250.            Public dwFlags As Integer
  251.  
  252.            ''' <summary>
  253.            '''
  254.            ''' </summary>
  255.            Public time As Integer
  256.  
  257.            ''' <summary>
  258.            '''
  259.            ''' </summary>
  260.            Public dwExtraInfo As IntPtr
  261.  
  262.        End Structure
  263.  
  264.        ''' <summary>
  265.        ''' Contains information about a simulated keyboard event.
  266.        ''' For more info see here:
  267.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
  268.        ''' </summary>
  269.        <Description("Structure used for 'ki' parameter of 'INPUT' structure")>
  270.        Friend Structure KEYBDINPUT
  271.  
  272.            ''' <summary>
  273.            ''' A virtual-key code.
  274.            ''' The code must be a value in the range '1' to '254'.
  275.            ''' If the 'dwFlags' member specifies 'KEYEVENTF_UNICODE', wVk must be '0'.
  276.            ''' </summary>
  277.            Public wVk As Short
  278.  
  279.            ''' <summary>
  280.            ''' A hardware scan code for the key.
  281.            ''' If 'dwFlags' specifies 'KEYEVENTF_UNICODE',
  282.            ''' 'wScan' specifies a Unicode character which is to be sent to the foreground application.
  283.            ''' </summary>
  284.            Public wScan As Short
  285.  
  286.            ''' <summary>
  287.            ''' Specifies various aspects of a keystroke.
  288.            ''' </summary>
  289.            Public dwFlags As KeyboardInput_Flags
  290.  
  291.            ''' <summary>
  292.            ''' The time stamp for the event, in milliseconds.
  293.            ''' If this parameter is '0', the system will provide its own time stamp.
  294.            ''' </summary>
  295.            Public time As Integer
  296.  
  297.            ''' <summary>
  298.            ''' An additional value associated with the keystroke.
  299.            ''' Use the 'GetMessageExtraInfo' function to obtain this information.
  300.            ''' </summary>
  301.            Public dwExtraInfo As IntPtr
  302.  
  303.        End Structure
  304.  
  305.        ''' <summary>
  306.        ''' Contains information about a simulated message generated by an input device other than a keyboard or mouse.
  307.        ''' For more info see here:
  308.        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646269%28v=vs.85%29.aspx
  309.        ''' </summary>
  310.        <Description("Structure used for 'hi' parameter of 'INPUT' structure")>
  311.        Friend Structure HARDWAREINPUT
  312.  
  313.            ''' <summary>
  314.            ''' The message generated by the input hardware.
  315.            ''' </summary>
  316.            Public uMsg As Integer
  317.  
  318.            ''' <summary>
  319.            ''' The low-order word of the lParam parameter for uMsg.
  320.            ''' </summary>
  321.            Public wParamL As Short
  322.  
  323.            ''' <summary>
  324.            ''' The high-order word of the lParam parameter for uMsg.
  325.            ''' </summary>
  326.            Public wParamH As Short
  327.  
  328.        End Structure
  329.  
  330. #End Region
  331.  
  332.    End Class
  333.  
  334. #End Region
  335.  
  336. #Region " Public Methods "
  337.  
  338.    ''' <summary>
  339.    ''' Sends a keystroke.
  340.    ''' </summary>
  341.    ''' <param name="key">
  342.    ''' Indicates the keystroke to simulate.
  343.    ''' </param>
  344.    ''' <param name="BlockInput">
  345.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  346.    ''' </param>
  347.    ''' <returns>
  348.    ''' The function returns the number of events that it successfully
  349.    ''' inserted into the keyboard or mouse input stream.
  350.    ''' If the function returns zero, the input was already blocked by another thread.
  351.    ''' </returns>
  352.    Public Shared Function SendKey(ByVal key As Char,
  353.                                   Optional BlockInput As Boolean = False) As Integer
  354.  
  355.        ' Block Keyboard and mouse.
  356.        If BlockInput Then NativeMethods.BlockInput(True)
  357.  
  358.        ' The inputs structures to send.
  359.        Dim Inputs As New List(Of NativeMethods.INPUT)
  360.  
  361.        ' The current input to add into the Inputs list.
  362.        Dim CurrentInput As New NativeMethods.INPUT
  363.  
  364.        ' Determines whether a character is an alphabetic letter.
  365.        Dim IsAlphabetic As Boolean = Not (key.ToString.ToUpper = key.ToString.ToLower)
  366.  
  367.        ' Determines whether a character is an uppercase alphabetic letter.
  368.        Dim IsUpperCase As Boolean =
  369.            (key.ToString = key.ToString.ToUpper) AndAlso Not (key.ToString.ToUpper = key.ToString.ToLower)
  370.  
  371.        ' Determines whether the CapsLock key is pressed down.
  372.        Dim CapsLockON As Boolean = My.Computer.Keyboard.CapsLock
  373.  
  374.        ' Set the passed key to upper-case.
  375.        If IsAlphabetic AndAlso Not IsUpperCase Then
  376.            key = Convert.ToChar(key.ToString.ToUpper)
  377.        End If
  378.  
  379.        ' If character is UpperCase and CapsLock is pressed down,
  380.        ' OrElse character is not UpperCase and CapsLock is not pressed down.
  381.        If (IsAlphabetic AndAlso IsUpperCase AndAlso CapsLockON) _
  382.        OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso Not CapsLockON) _
  383.        OrElse (Not IsAlphabetic) Then
  384.  
  385.            ' Hold the character key.
  386.            With CurrentInput
  387.                .type = NativeMethods.InputType.Keyboard
  388.                .ki.wVk = Convert.ToInt16(CChar(key))
  389.                .ki.dwFlags = 0
  390.            End With : Inputs.Add(CurrentInput)
  391.  
  392.            ' Release the character key.
  393.            With CurrentInput
  394.                .type = NativeMethods.InputType.Keyboard
  395.                .ki.wVk = Convert.ToInt16(CChar(key))
  396.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  397.            End With : Inputs.Add(CurrentInput)
  398.  
  399.            ' If character is UpperCase and CapsLock is not pressed down,
  400.            ' OrElse character is not UpperCase and CapsLock is pressed down.
  401.        ElseIf (IsAlphabetic AndAlso IsUpperCase AndAlso Not CapsLockON) _
  402.        OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso CapsLockON) Then
  403.  
  404.            ' Hold the Shift key.
  405.            With CurrentInput
  406.                .type = NativeMethods.InputType.Keyboard
  407.                .ki.wVk = NativeMethods.VirtualKeys.SHIFT
  408.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
  409.            End With : Inputs.Add(CurrentInput)
  410.  
  411.            ' Hold the character key.
  412.            With CurrentInput
  413.                .type = NativeMethods.InputType.Keyboard
  414.                .ki.wVk = Convert.ToInt16(CChar(key))
  415.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
  416.            End With : Inputs.Add(CurrentInput)
  417.  
  418.            ' Release the character key.
  419.            With CurrentInput
  420.                .type = NativeMethods.InputType.Keyboard
  421.                .ki.wVk = Convert.ToInt16(CChar(key))
  422.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  423.            End With : Inputs.Add(CurrentInput)
  424.  
  425.            ' Release the Shift key.
  426.            With CurrentInput
  427.                .type = NativeMethods.InputType.Keyboard
  428.                .ki.wVk = NativeMethods.VirtualKeys.SHIFT
  429.                .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
  430.            End With : Inputs.Add(CurrentInput)
  431.  
  432.        End If ' UpperCase And My.Computer.Keyboard.CapsLock is...
  433.  
  434.        ' Send the input key.
  435.        Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
  436.                                       Marshal.SizeOf(GetType(NativeMethods.INPUT)))
  437.  
  438.        ' Unblock Keyboard and mouse.
  439.        If BlockInput Then NativeMethods.BlockInput(False)
  440.  
  441.    End Function
  442.  
  443.    ''' <summary>
  444.    ''' Sends a keystroke.
  445.    ''' </summary>
  446.    ''' <param name="key">
  447.    ''' Indicates the keystroke to simulate.
  448.    ''' </param>
  449.    ''' <param name="BlockInput">
  450.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  451.    ''' </param>
  452.    ''' <returns>
  453.    ''' The function returns the number of events that it successfully
  454.    ''' inserted into the keyboard or mouse input stream.
  455.    ''' If the function returns zero, the input was already blocked by another thread.
  456.    ''' </returns>
  457.    Public Shared Function SendKey(ByVal key As Keys,
  458.                                   Optional BlockInput As Boolean = False) As Integer
  459.  
  460.        Return SendKey(Convert.ToChar(key), BlockInput)
  461.  
  462.    End Function
  463.  
  464.    ''' <summary>
  465.    ''' Sends a string.
  466.    ''' </summary>
  467.    ''' <param name="String">
  468.    ''' Indicates the string to send.
  469.    ''' </param>
  470.    ''' <param name="BlockInput">
  471.    ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
  472.    ''' </param>
  473.    ''' <returns>
  474.    ''' The function returns the number of events that it successfully
  475.    ''' inserted into the keyboard or mouse input stream.
  476.    ''' If the function returns zero, the input was already blocked by another thread.
  477.    ''' </returns>
  478.    Public Shared Function SendKeys(ByVal [String] As String,
  479.                                    Optional BlockInput As Boolean = False) As Integer
  480.  
  481.        Dim SuccessCount As Integer = 0
  482.  
  483.        ' Block Keyboard and mouse.
  484.        If BlockInput Then NativeMethods.BlockInput(True)
  485.  
  486.        For Each c As Char In [String]
  487.            SuccessCount += SendKey(c, BlockInput:=False)
  488.        Next c
  489.  
  490.        ' Unblock Keyboard and mouse.
  491.        If BlockInput Then NativeMethods.BlockInput(False)
  492.  
  493.        Return SuccessCount
  494.  
  495.    End Function
  496.  
  497. #End Region
  498.  
  499. End Class

Saludos
7578  Programación / .NET (C#, VB.NET, ASP) / Re: [Duda]¿Como detectar los usb con vb 2013? en: 18 Febrero 2014, 05:00 am
Has justificado bien todo lo que has dicho y te doy la razón, solo quiero comentar una cosa:

Citar
Creo que no es muy justo tratar de morralla al trabajo que han hecho otros con el mismo trabajo (o más)

Claro que no, mi intención no era dar a pensar eso, si un trabajo está echo en vb5/vb6 con los métodos de vb, a mi me parece perfecto.

Pero, en VB.NET, la diferencia entre algo que está echo en 5 minutos copiando códigos de VB6, y algo que está echo en horas, dias, semanas o meses se aprecia la diferencia.

Creo que has visto muy pocos source-codes desarrollados en VB.NET que básicamente todos los métodos usados son de VB6 (por desgracia yo he visto más de los que quisiera), te aseguro que hay demasiados, he visto gente muy experta que siguen mal acostumbrados a esas prácticas,
e incluso el tipo de declaración de APIS que usan (Declare function...), eso me parece lamentable hacerlo en VB.NET porque no aprovechan ninguna ventaja de .NET Framework como el tipo de declaraciones de APIS que he comentado (dllimport),
así pues, una persona que trabaja duro y le pone ganas no haría esas cosas, es puro copy/paste de VB6, a eso me refiero con morralla,
es una mania que yo tengo, pero lo llevo mal ver códigos de .NET vb6-stylized (como se suele decir por ahí...).

Saludos!
7579  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 17 Febrero 2014, 22:16 pm
obtener los dispositivos extraibles que están conectados al sistema

Código
  1.        ' GetDrivesOfType
  2.       ' ( By Elektro )
  3.       '
  4.       ' Usage Examples:
  5.       '
  6.       ' Dim Drives As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Fixed)
  7.       '
  8.       ' For Each Drive As IO.DriveInfo In GetDrivesOfType(IO.DriveType.Removable)
  9.       '     MsgBox(Drive.Name)
  10.       ' Next Drive
  11.       '
  12.       ''' <summary>
  13.       ''' Get all the connected drives of the given type.
  14.       ''' </summary>
  15.       ''' <param name="DriveType">Indicates the type of the drive.</param>
  16.       ''' <returns>System.IO.DriveInfo[].</returns>
  17.       Public Function GetDrivesOfType(ByVal DriveType As IO.DriveType) As IO.DriveInfo()
  18.  
  19.           Return (From Drive As IO.DriveInfo In IO.DriveInfo.GetDrives
  20.                   Where Drive.DriveType = DriveType).ToArray
  21.  
  22.       End Function



monitorizar la inserción/extracción de dispositivos

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-17-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DriveWatcher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ' ''' <summary>
  13. ' ''' The DriveWatcher instance to monitor USB devices.
  14. ' ''' </summary>
  15. 'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me)
  16.  
  17. ' ''' <summary>
  18. ' ''' Handles the DriveInserted event of the USBMonitor object.
  19. ' ''' </summary>
  20. ' ''' <param name="sender">The source of the event.</param>
  21. ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  22. 'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted
  23.  
  24. '    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
  25.  
  26. '        Dim sb As New System.Text.StringBuilder
  27.  
  28. '        sb.AppendLine("DRIVE CONNECTED!")
  29. '        sb.AppendLine()
  30. '        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
  31. '        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
  32. '        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
  33. '        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
  34. '        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
  35. '        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
  36. '        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
  37. '        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
  38. '        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
  39.  
  40. '        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
  41.  
  42. '    End If
  43.  
  44. 'End Sub
  45.  
  46. ' ''' <summary>
  47. ' ''' Handles the DriveRemoved event of the USBMonitor object.
  48. ' ''' </summary>
  49. ' ''' <param name="sender">The source of the event.</param>
  50. ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  51. 'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved
  52.  
  53. '    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
  54.  
  55. '        Dim sb As New System.Text.StringBuilder
  56.  
  57. '        sb.AppendLine("DRIVE DISCONNECTED!")
  58. '        sb.AppendLine()
  59. '        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
  60. '        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
  61. '        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
  62. '        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
  63. '        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
  64. '        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
  65. '        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
  66. '        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
  67. '        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
  68.  
  69. '        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
  70.  
  71. '    End If
  72.  
  73. 'End Sub
  74.  
  75. #End Region
  76.  
  77. #Region " Imports "
  78.  
  79. Imports System.IO
  80. Imports System.Runtime.InteropServices
  81. Imports System.ComponentModel
  82.  
  83. #End Region
  84.  
  85. ''' <summary>
  86. ''' Device insertion/removal monitor.
  87. ''' </summary>
  88. Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
  89.  
  90. #Region " Objects "
  91.  
  92.    ''' <summary>
  93.    ''' The current connected drives.
  94.    ''' </summary>
  95.    Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo)
  96.  
  97.    ''' <summary>
  98.    ''' Indicates the drive letter of the current device.
  99.    ''' </summary>
  100.    Private DriveLetter As Char = Nothing
  101.  
  102.    ''' <summary>
  103.    ''' Indicates the current Drive information.
  104.    ''' </summary>
  105.    Private CurrentDrive As DriveWatcherInfo = Nothing
  106.  
  107.    ''' <summary>
  108.    ''' The form to manage their Windows Messages.
  109.    ''' </summary>
  110.    Private WithEvents form As Form = Nothing
  111.  
  112. #End Region
  113.  
  114. #Region " Events "
  115.  
  116.    ''' <summary>
  117.    ''' Occurs when a drive is inserted.
  118.    ''' </summary>
  119.    Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo)
  120.  
  121.    ''' <summary>
  122.    ''' Occurs when a drive is removed.
  123.    ''' </summary>
  124.    Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo)
  125.  
  126. #End Region
  127.  
  128. #Region " Enumerations "
  129.  
  130.    ''' <summary>
  131.    ''' Notifies an application of a change to the hardware configuration of a device or the computer.
  132.    ''' A window receives this message through its WindowProc function.
  133.    ''' For more info, see here:
  134.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx
  135.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx
  136.    ''' </summary>
  137.    Private Enum DeviceEvents As Integer
  138.  
  139.        ''' <summary>
  140.        ''' The current configuration has changed, due to a dock or undock.
  141.        ''' </summary>
  142.        Change = &H219
  143.  
  144.        ''' <summary>
  145.        ''' A device or piece of media has been inserted and becomes available.
  146.        ''' </summary>
  147.        Arrival = &H8000
  148.  
  149.        ''' <summary>
  150.        ''' Request permission to remove a device or piece of media.
  151.        ''' This message is the last chance for applications and drivers to prepare for this removal.
  152.        ''' However, any application can deny this request and cancel the operation.
  153.        ''' </summary>
  154.        QueryRemove = &H8001
  155.  
  156.        ''' <summary>
  157.        ''' A request to remove a device or piece of media has been canceled.
  158.        ''' </summary>
  159.        QueryRemoveFailed = &H8002
  160.  
  161.        ''' <summary>
  162.        ''' A device or piece of media is being removed and is no longer available for use.
  163.        ''' </summary>
  164.        RemovePending = &H8003
  165.  
  166.        ''' <summary>
  167.        ''' A device or piece of media has been removed.
  168.        ''' </summary>
  169.        RemoveComplete = &H8004
  170.  
  171.        ''' <summary>
  172.        ''' The type volume
  173.        ''' </summary>
  174.        TypeVolume = &H2
  175.  
  176.    End Enum
  177.  
  178. #End Region
  179.  
  180. #Region " Structures "
  181.  
  182.    ''' <summary>
  183.    ''' Indicates information related of a Device.
  184.    ''' ( Replic of System.IO.DriveInfo )
  185.    ''' </summary>
  186.    Public Structure DriveWatcherInfo
  187.  
  188.        ''' <summary>
  189.        ''' Indicates the name of a drive, such as 'C:\'.
  190.        ''' </summary>
  191.        Public Name As String
  192.  
  193.        ''' <summary>
  194.        ''' Indicates the amount of available free space on a drive, in bytes.
  195.        ''' </summary>
  196.        Public AvailableFreeSpace As Long
  197.  
  198.        ''' <summary>
  199.        ''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc...
  200.        ''' </summary>
  201.        Public DriveFormat As String
  202.  
  203.        ''' <summary>
  204.        ''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc...
  205.        ''' </summary>
  206.        Public DriveType As DriveType
  207.  
  208.        ''' <summary>
  209.        ''' Indicates whether a drive is ready.
  210.        ''' </summary>
  211.        Public IsReady As Boolean
  212.  
  213.        ''' <summary>
  214.        ''' Indicates the root directory of a drive.
  215.        ''' </summary>
  216.        Public RootDirectory As String
  217.  
  218.        ''' <summary>
  219.        ''' Indicates the total amount of free space available on a drive, in bytes.
  220.        ''' </summary>
  221.        Public TotalFreeSpace As Long
  222.  
  223.        ''' <summary>
  224.        ''' Indicates the total size of storage space on a drive, in bytes.
  225.        ''' </summary>
  226.        Public TotalSize As Long
  227.  
  228.        ''' <summary>
  229.        ''' Indicates the volume label of a drive.
  230.        ''' </summary>
  231.        Public VolumeLabel As String
  232.  
  233.        ''' <summary>
  234.        ''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct.
  235.        ''' </summary>
  236.        ''' <param name="e">The e.</param>
  237.        Public Sub New(ByVal e As DriveInfo)
  238.  
  239.            Name = e.Name
  240.  
  241.            Select Case e.IsReady
  242.  
  243.                Case True ' Drive is formatted and ready.
  244.                    IsReady = True
  245.                    DriveFormat = e.DriveFormat
  246.                    DriveType = e.DriveType
  247.                    RootDirectory = e.RootDirectory.FullName
  248.                    VolumeLabel = e.VolumeLabel
  249.                    TotalSize = e.TotalSize
  250.                    TotalFreeSpace = e.TotalFreeSpace
  251.                    AvailableFreeSpace = e.AvailableFreeSpace
  252.  
  253.                Case False ' Drive is not formatted so can't retrieve data.
  254.                    IsReady = False
  255.                    DriveFormat = Nothing
  256.                    DriveType = e.DriveType
  257.                    RootDirectory = e.RootDirectory.FullName
  258.                    VolumeLabel = Nothing
  259.                    TotalSize = 0
  260.                    TotalFreeSpace = 0
  261.                    AvailableFreeSpace = 0
  262.  
  263.            End Select ' e.IsReady
  264.  
  265.        End Sub
  266.  
  267.    End Structure
  268.  
  269.    ''' <summary>
  270.    ''' Contains information about a logical volume.
  271.    ''' For more info, see here:
  272.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx
  273.    ''' </summary>
  274.    <StructLayout(LayoutKind.Sequential)>
  275.    Private Structure DEV_BROADCAST_VOLUME
  276.  
  277.        ''' <summary>
  278.        ''' The size of this structure, in bytes.
  279.        ''' </summary>
  280.        Public Size As UInteger
  281.  
  282.        ''' <summary>
  283.        ''' Set to DBT_DEVTYP_VOLUME (2).
  284.        ''' </summary>
  285.        Public Type As UInteger
  286.  
  287.        ''' <summary>
  288.        ''' Reserved parameter; do not use this.
  289.        ''' </summary>
  290.        Public Reserved As UInteger
  291.  
  292.        ''' <summary>
  293.        ''' The logical unit mask identifying one or more logical units.
  294.        ''' Each bit in the mask corresponds to one logical drive.
  295.        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
  296.        ''' </summary>
  297.        Public Mask As UInteger
  298.  
  299.        ''' <summary>
  300.        ''' This parameter can be one of the following values:
  301.        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
  302.        ''' '0x0002': Indicated logical volume is a network volume.
  303.        ''' </summary>
  304.        Public Flags As UShort
  305.  
  306.    End Structure
  307.  
  308. #End Region
  309.  
  310. #Region " Constructor "
  311.  
  312.    ''' <summary>
  313.    ''' Initializes a new instance of this class.
  314.    ''' </summary>
  315.    ''' <param name="form">The form to assign.</param>
  316.    Public Sub New(ByVal form As Form)
  317.  
  318.        ' Assign the Formulary.
  319.        Me.form = form
  320.  
  321.    End Sub
  322.  
  323. #End Region
  324.  
  325. #Region " Event Handlers "
  326.  
  327.    ''' <summary>
  328.    ''' Assign the handle of the target Form to this NativeWindow,
  329.    ''' necessary to override target Form's WndProc.
  330.    ''' </summary>
  331.    Private Sub SetFormHandle() _
  332.    Handles form.HandleCreated, form.Load, form.Shown
  333.  
  334.        If Not MyBase.Handle.Equals(Me.form.Handle) Then
  335.            MyBase.AssignHandle(Me.form.Handle)
  336.        End If
  337.  
  338.    End Sub
  339.  
  340.    ''' <summary>
  341.    ''' Releases the Handle.
  342.    ''' </summary>
  343.    Private Sub OnHandleDestroyed() _
  344.    Handles form.HandleDestroyed
  345.  
  346.        MyBase.ReleaseHandle()
  347.  
  348.    End Sub
  349.  
  350. #End Region
  351.  
  352. #Region " Private Methods "
  353.  
  354.    ''' <summary>
  355.    ''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object.
  356.    ''' </summary>
  357.    ''' <param name="Device">
  358.    ''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask.
  359.    ''' </param>
  360.    ''' <returns>System.Char.</returns>
  361.    Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char
  362.  
  363.        Dim DriveLetters As Char() =
  364.            {
  365.            "A", "B", "C", "D", "E", "F", "G", "H", "I",
  366.            "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  367.            "S", "T", "U", "V", "W", "X", "Y", "Z"
  368.            }
  369.  
  370.        Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask))
  371.  
  372.        For X As Integer = 0 To DeviceID.Length
  373.  
  374.            If DeviceID(X) Then
  375.                Return DriveLetters(X)
  376.            End If
  377.  
  378.        Next X
  379.  
  380.        Return Nothing
  381.  
  382.    End Function
  383.  
  384. #End Region
  385.  
  386. #Region " WndProc"
  387.  
  388.    ''' <summary>
  389.    ''' Invokes the default window procedure associated with this window to process messages for this Window.
  390.    ''' </summary>
  391.    ''' <param name="m">
  392.    ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
  393.    ''' </param>
  394.    Protected Overrides Sub WndProc(ByRef m As Message)
  395.  
  396.        Select Case m.Msg
  397.  
  398.            Case DeviceEvents.Change ' The hardware has changed.
  399.  
  400.                ' Transform the LParam pointer into the data structure.
  401.                Dim CurrentWDrive As DEV_BROADCAST_VOLUME =
  402.                    CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)
  403.  
  404.                Select Case m.WParam.ToInt32
  405.  
  406.                    Case DeviceEvents.Arrival ' The device is connected.
  407.  
  408.                        ' Get the drive letter of the connected device.
  409.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  410.  
  411.                        ' Get the drive information of the connected device.
  412.                        CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
  413.  
  414.                        ' If it's an storage device then...
  415.                        If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then
  416.  
  417.                            ' Inform that the device is connected by raising the 'DriveConnected' event.
  418.                            RaiseEvent DriveInserted(Me, CurrentDrive)
  419.  
  420.                            ' Add the connected device to the dictionary, to retrieve info.
  421.                            If Not CurrentDrives.ContainsKey(DriveLetter) Then
  422.  
  423.                                CurrentDrives.Add(DriveLetter, CurrentDrive)
  424.  
  425.                            End If ' Not CurrentDrives.ContainsKey(DriveLetter)
  426.  
  427.                        End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume
  428.  
  429.                    Case DeviceEvents.QueryRemove ' The device is preparing to be removed.
  430.  
  431.                        ' Get the letter of the current device being removed.
  432.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  433.  
  434.                        ' If the current device being removed is not in the dictionary then...
  435.                        If Not CurrentDrives.ContainsKey(DriveLetter) Then
  436.  
  437.                            ' Get the device information of the current device being removed.
  438.                            CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
  439.  
  440.                            ' Add the current device to the dictionary,
  441.                            ' to retrieve info before lost it after fully-removal.
  442.                            CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter)))
  443.  
  444.                        End If ' Not CurrentDrives.ContainsKey(DriveLetter)
  445.  
  446.                    Case DeviceEvents.RemoveComplete
  447.  
  448.                        ' Get the letter of the removed device.
  449.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  450.  
  451.                        ' Inform that the device is disconnected by raising the 'DriveDisconnected' event.
  452.                        RaiseEvent DriveRemoved(Me, CurrentDrive)
  453.  
  454.                        ' If the removed device is in the dictionary then...
  455.                        If CurrentDrives.ContainsKey(DriveLetter) Then
  456.  
  457.                            ' Remove the device from the dictionary.
  458.                            CurrentDrives.Remove(DriveLetter)
  459.  
  460.                        End If ' CurrentDrives.ContainsKey(DriveLetter)
  461.  
  462.                End Select ' m.WParam.ToInt32
  463.  
  464.        End Select ' m.Msg
  465.  
  466.        MyBase.WndProc(m) ' Return Message to base message handler.
  467.  
  468.    End Sub
  469.  
  470. #End Region
  471.  
  472. #Region " Hidden methods "
  473.  
  474.    ' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
  475.    ' NOTE: The methods can be re-enabled at any-time if needed.
  476.  
  477.    ''' <summary>
  478.    ''' Assigns a handle to this window.
  479.    ''' </summary>
  480.    <EditorBrowsable(EditorBrowsableState.Never)>
  481.    Public Shadows Sub AssignHandle()
  482.    End Sub
  483.  
  484.    ''' <summary>
  485.    ''' Creates a window and its handle with the specified creation parameters.
  486.    ''' </summary>
  487.    <EditorBrowsable(EditorBrowsableState.Never)>
  488.    Public Shadows Sub CreateHandle()
  489.    End Sub
  490.  
  491.    ''' <summary>
  492.    ''' Creates an object that contains all the relevant information required
  493.    ''' to generate a proxy used to communicate with a remote object.
  494.    ''' </summary>
  495.    <EditorBrowsable(EditorBrowsableState.Never)>
  496.    Public Shadows Sub CreateObjRef()
  497.    End Sub
  498.  
  499.    ''' <summary>
  500.    ''' Invokes the default window procedure associated with this window.
  501.    ''' </summary>
  502.    <EditorBrowsable(EditorBrowsableState.Never)>
  503.    Public Shadows Sub DefWndProc()
  504.    End Sub
  505.  
  506.    ''' <summary>
  507.    ''' Destroys the window and its handle.
  508.    ''' </summary>
  509.    <EditorBrowsable(EditorBrowsableState.Never)>
  510.    Public Shadows Sub DestroyHandle()
  511.    End Sub
  512.  
  513.    ''' <summary>
  514.    ''' Determines whether the specified object is equal to the current object.
  515.    ''' </summary>
  516.    <EditorBrowsable(EditorBrowsableState.Never)>
  517.    Public Shadows Sub Equals()
  518.    End Sub
  519.  
  520.    ''' <summary>
  521.    ''' Serves as the default hash function.
  522.    ''' </summary>
  523.    <EditorBrowsable(EditorBrowsableState.Never)>
  524.    Public Shadows Sub GetHashCode()
  525.    End Sub
  526.  
  527.    ''' <summary>
  528.    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
  529.    ''' </summary>
  530.    <EditorBrowsable(EditorBrowsableState.Never)>
  531.    Public Shadows Sub GetLifetimeService()
  532.    End Sub
  533.  
  534.    ''' <summary>
  535.    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
  536.    ''' </summary>
  537.    <EditorBrowsable(EditorBrowsableState.Never)>
  538.    Public Shadows Sub InitializeLifetimeService()
  539.    End Sub
  540.  
  541.    ''' <summary>
  542.    ''' Releases the handle associated with this window.
  543.    ''' </summary>
  544.    <EditorBrowsable(EditorBrowsableState.Never)>
  545.    Public Shadows Sub ReleaseHandle()
  546.    End Sub
  547.  
  548.    ''' <summary>
  549.    ''' Gets the handle for this window.
  550.    ''' </summary>
  551.    <EditorBrowsable(EditorBrowsableState.Never)>
  552.    Public Shadows Property Handle()
  553.  
  554. #End Region
  555.  
  556. #Region " IDisposable "
  557.  
  558.    ''' <summary>
  559.    ''' To detect redundant calls when disposing.
  560.    ''' </summary>
  561.    Private IsDisposed As Boolean = False
  562.  
  563.    ''' <summary>
  564.    ''' Prevent calls to methods after disposing.
  565.    ''' </summary>
  566.    ''' <exception cref="System.ObjectDisposedException"></exception>
  567.    Private Sub DisposedCheck()
  568.        If Me.IsDisposed Then
  569.            Throw New ObjectDisposedException(Me.GetType().FullName)
  570.        End If
  571.    End Sub
  572.  
  573.    ''' <summary>
  574.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  575.    ''' </summary>
  576.    Public Sub Dispose() Implements IDisposable.Dispose
  577.        Dispose(True)
  578.        GC.SuppressFinalize(Me)
  579.    End Sub
  580.  
  581.    ''' <summary>
  582.    ''' Releases unmanaged and - optionally - managed resources.
  583.    ''' </summary>
  584.    ''' <param name="IsDisposing">
  585.    ''' <c>true</c> to release both managed and unmanaged resources;
  586.    ''' <c>false</c> to release only unmanaged resources.
  587.    ''' </param>
  588.    Protected Sub Dispose(ByVal IsDisposing As Boolean)
  589.  
  590.        If Not Me.IsDisposed Then
  591.  
  592.            If IsDisposing Then
  593.                Me.form = Nothing
  594.                MyBase.ReleaseHandle()
  595.                MyBase.DestroyHandle()
  596.            End If
  597.  
  598.        End If
  599.  
  600.        Me.IsDisposed = True
  601.  
  602.    End Sub
  603.  
  604. #End Region
  605.  
  606. End Class
7580  Programación / .NET (C#, VB.NET, ASP) / Re: [Duda]¿Como detectar los usb con vb 2013? en: 17 Febrero 2014, 21:55 pm
( Escribo este doble post justificado porque no cabía el siguiente código, maldito límite de caracteres  :rolleyes: )

¿Como monitorizar la inserción/extracción de dispositivos USB's?:

Si estás corriendo Windows 8 o Win server 2012 entonces puedes usar la Class DeviceWatcher que prácticamente te hace todo el trabajo sucio xD, eso si, es para apps de Metro así que debes referenciar la librería 'WindowsRuntime.dll' y 'Windows.Foundation' en caso de que tu proyecto sea un WinForms/WPF.

De todas formas he ideado este ayudante (bueno, en realidad es un código antiguo que escribí hace tiempo, pero lo he actualizado y mejorado) que no necesita el uso de Windows 8, y en el cual solo tienes que manejar dos eventos, 'DriveInserted' y 'DriveRemoved', más sencillo imposible.

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 02-17-2014
  4. ' ***********************************************************************
  5. ' <copyright file="DriveWatcher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. ' ''' <summary>
  13. ' ''' The DriveWatcher instance to monitor USB devices.
  14. ' ''' </summary>
  15. 'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me)
  16.  
  17. ' ''' <summary>
  18. ' ''' Handles the DriveInserted event of the USBMonitor object.
  19. ' ''' </summary>
  20. ' ''' <param name="sender">The source of the event.</param>
  21. ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  22. 'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted
  23.  
  24. '    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
  25.  
  26. '        Dim sb As New System.Text.StringBuilder
  27.  
  28. '        sb.AppendLine("DRIVE CONNECTED!")
  29. '        sb.AppendLine()
  30. '        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
  31. '        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
  32. '        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
  33. '        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
  34. '        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
  35. '        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
  36. '        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
  37. '        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
  38. '        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
  39.  
  40. '        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
  41.  
  42. '    End If
  43.  
  44. 'End Sub
  45.  
  46. ' ''' <summary>
  47. ' ''' Handles the DriveRemoved event of the USBMonitor object.
  48. ' ''' </summary>
  49. ' ''' <param name="sender">The source of the event.</param>
  50. ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  51. 'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved
  52.  
  53. '    If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then...
  54.  
  55. '        Dim sb As New System.Text.StringBuilder
  56.  
  57. '        sb.AppendLine("DRIVE DISCONNECTED!")
  58. '        sb.AppendLine()
  59. '        sb.AppendLine(String.Format("Drive Name: {0}", e.Name))
  60. '        sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType))
  61. '        sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat))
  62. '        sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady))
  63. '        sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory))
  64. '        sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel))
  65. '        sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize))
  66. '        sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace))
  67. '        sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace))
  68.  
  69. '        MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information)
  70.  
  71. '    End If
  72.  
  73. 'End Sub
  74.  
  75. #End Region
  76.  
  77. #Region " Imports "
  78.  
  79. Imports System.IO
  80. Imports System.Runtime.InteropServices
  81. Imports System.ComponentModel
  82.  
  83. #End Region
  84.  
  85. ''' <summary>
  86. ''' Device insertion/removal monitor.
  87. ''' </summary>
  88. Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable
  89.  
  90. #Region " Objects "
  91.  
  92.    ''' <summary>
  93.    ''' The current connected drives.
  94.    ''' </summary>
  95.    Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo)
  96.  
  97.    ''' <summary>
  98.    ''' Indicates the drive letter of the current device.
  99.    ''' </summary>
  100.    Private DriveLetter As Char = Nothing
  101.  
  102.    ''' <summary>
  103.    ''' Indicates the current Drive information.
  104.    ''' </summary>
  105.    Private CurrentDrive As DriveWatcherInfo = Nothing
  106.  
  107.    ''' <summary>
  108.    ''' The form to manage their Windows Messages.
  109.    ''' </summary>
  110.    Private WithEvents form As Form = Nothing
  111.  
  112. #End Region
  113.  
  114. #Region " Events "
  115.  
  116.    ''' <summary>
  117.    ''' Occurs when a drive is inserted.
  118.    ''' </summary>
  119.    Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo)
  120.  
  121.    ''' <summary>
  122.    ''' Occurs when a drive is removed.
  123.    ''' </summary>
  124.    Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo)
  125.  
  126. #End Region
  127.  
  128. #Region " Enumerations "
  129.  
  130.    ''' <summary>
  131.    ''' Notifies an application of a change to the hardware configuration of a device or the computer.
  132.    ''' A window receives this message through its WindowProc function.
  133.    ''' For more info, see here:
  134.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx
  135.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx
  136.    ''' </summary>
  137.    Private Enum DeviceEvents As Integer
  138.  
  139.        ''' <summary>
  140.        ''' The current configuration has changed, due to a dock or undock.
  141.        ''' </summary>
  142.        Change = &H219
  143.  
  144.        ''' <summary>
  145.        ''' A device or piece of media has been inserted and becomes available.
  146.        ''' </summary>
  147.        Arrival = &H8000
  148.  
  149.        ''' <summary>
  150.        ''' Request permission to remove a device or piece of media.
  151.        ''' This message is the last chance for applications and drivers to prepare for this removal.
  152.        ''' However, any application can deny this request and cancel the operation.
  153.        ''' </summary>
  154.        QueryRemove = &H8001
  155.  
  156.        ''' <summary>
  157.        ''' A request to remove a device or piece of media has been canceled.
  158.        ''' </summary>
  159.        QueryRemoveFailed = &H8002
  160.  
  161.        ''' <summary>
  162.        ''' A device or piece of media is being removed and is no longer available for use.
  163.        ''' </summary>
  164.        RemovePending = &H8003
  165.  
  166.        ''' <summary>
  167.        ''' A device or piece of media has been removed.
  168.        ''' </summary>
  169.        RemoveComplete = &H8004
  170.  
  171.        ''' <summary>
  172.        ''' The type volume
  173.        ''' </summary>
  174.        TypeVolume = &H2
  175.  
  176.    End Enum
  177.  
  178. #End Region
  179.  
  180. #Region " Structures "
  181.  
  182.    ''' <summary>
  183.    ''' Indicates information related of a Device.
  184.    ''' ( Replic of System.IO.DriveInfo )
  185.    ''' </summary>
  186.    Public Structure DriveWatcherInfo
  187.  
  188.        ''' <summary>
  189.        ''' Indicates the name of a drive, such as 'C:\'.
  190.        ''' </summary>
  191.        Public Name As String
  192.  
  193.        ''' <summary>
  194.        ''' Indicates the amount of available free space on a drive, in bytes.
  195.        ''' </summary>
  196.        Public AvailableFreeSpace As Long
  197.  
  198.        ''' <summary>
  199.        ''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc...
  200.        ''' </summary>
  201.        Public DriveFormat As String
  202.  
  203.        ''' <summary>
  204.        ''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc...
  205.        ''' </summary>
  206.        Public DriveType As DriveType
  207.  
  208.        ''' <summary>
  209.        ''' Indicates whether a drive is ready.
  210.        ''' </summary>
  211.        Public IsReady As Boolean
  212.  
  213.        ''' <summary>
  214.        ''' Indicates the root directory of a drive.
  215.        ''' </summary>
  216.        Public RootDirectory As String
  217.  
  218.        ''' <summary>
  219.        ''' Indicates the total amount of free space available on a drive, in bytes.
  220.        ''' </summary>
  221.        Public TotalFreeSpace As Long
  222.  
  223.        ''' <summary>
  224.        ''' Indicates the total size of storage space on a drive, in bytes.
  225.        ''' </summary>
  226.        Public TotalSize As Long
  227.  
  228.        ''' <summary>
  229.        ''' Indicates the volume label of a drive.
  230.        ''' </summary>
  231.        Public VolumeLabel As String
  232.  
  233.        ''' <summary>
  234.        ''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct.
  235.        ''' </summary>
  236.        ''' <param name="e">The e.</param>
  237.        Public Sub New(ByVal e As DriveInfo)
  238.  
  239.            Name = e.Name
  240.  
  241.            Select Case e.IsReady
  242.  
  243.                Case True ' Drive is formatted and ready.
  244.                    IsReady = True
  245.                    DriveFormat = e.DriveFormat
  246.                    DriveType = e.DriveType
  247.                    RootDirectory = e.RootDirectory.FullName
  248.                    VolumeLabel = e.VolumeLabel
  249.                    TotalSize = e.TotalSize
  250.                    TotalFreeSpace = e.TotalFreeSpace
  251.                    AvailableFreeSpace = e.AvailableFreeSpace
  252.  
  253.                Case False ' Drive is not formatted so can't retrieve data.
  254.                    IsReady = False
  255.                    DriveFormat = Nothing
  256.                    DriveType = e.DriveType
  257.                    RootDirectory = e.RootDirectory.FullName
  258.                    VolumeLabel = Nothing
  259.                    TotalSize = 0
  260.                    TotalFreeSpace = 0
  261.                    AvailableFreeSpace = 0
  262.  
  263.            End Select ' e.IsReady
  264.  
  265.        End Sub
  266.  
  267.    End Structure
  268.  
  269.    ''' <summary>
  270.    ''' Contains information about a logical volume.
  271.    ''' For more info, see here:
  272.    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx
  273.    ''' </summary>
  274.    <StructLayout(LayoutKind.Sequential)>
  275.    Private Structure DEV_BROADCAST_VOLUME
  276.  
  277.        ''' <summary>
  278.        ''' The size of this structure, in bytes.
  279.        ''' </summary>
  280.        Public Size As UInteger
  281.  
  282.        ''' <summary>
  283.        ''' Set to DBT_DEVTYP_VOLUME (2).
  284.        ''' </summary>
  285.        Public Type As UInteger
  286.  
  287.        ''' <summary>
  288.        ''' Reserved parameter; do not use this.
  289.        ''' </summary>
  290.        Public Reserved As UInteger
  291.  
  292.        ''' <summary>
  293.        ''' The logical unit mask identifying one or more logical units.
  294.        ''' Each bit in the mask corresponds to one logical drive.
  295.        ''' Bit 0 represents drive A, bit 1 represents drive B, and so on.
  296.        ''' </summary>
  297.        Public Mask As UInteger
  298.  
  299.        ''' <summary>
  300.        ''' This parameter can be one of the following values:
  301.        ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive.
  302.        ''' '0x0002': Indicated logical volume is a network volume.
  303.        ''' </summary>
  304.        Public Flags As UShort
  305.  
  306.    End Structure
  307.  
  308. #End Region
  309.  
  310. #Region " Constructor "
  311.  
  312.    ''' <summary>
  313.    ''' Initializes a new instance of this class.
  314.    ''' </summary>
  315.    ''' <param name="form">The form to assign.</param>
  316.    Public Sub New(ByVal form As Form)
  317.  
  318.        ' Assign the Formulary.
  319.        Me.form = form
  320.  
  321.    End Sub
  322.  
  323. #End Region
  324.  
  325. #Region " Event Handlers "
  326.  
  327.    ''' <summary>
  328.    ''' Assign the handle of the target Form to this NativeWindow,
  329.    ''' necessary to override target Form's WndProc.
  330.    ''' </summary>
  331.    Private Sub SetFormHandle() _
  332.    Handles form.HandleCreated, form.Load, form.Shown
  333.  
  334.        If Not MyBase.Handle.Equals(Me.form.Handle) Then
  335.            MyBase.AssignHandle(Me.form.Handle)
  336.        End If
  337.  
  338.    End Sub
  339.  
  340.    ''' <summary>
  341.    ''' Releases the Handle.
  342.    ''' </summary>
  343.    Private Sub OnHandleDestroyed() _
  344.    Handles form.HandleDestroyed
  345.  
  346.        MyBase.ReleaseHandle()
  347.  
  348.    End Sub
  349.  
  350. #End Region
  351.  
  352. #Region " Private Methods "
  353.  
  354.    ''' <summary>
  355.    ''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object.
  356.    ''' </summary>
  357.    ''' <param name="Device">
  358.    ''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask.
  359.    ''' </param>
  360.    ''' <returns>System.Char.</returns>
  361.    Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char
  362.  
  363.        Dim DriveLetters As Char() =
  364.            {
  365.            "A", "B", "C", "D", "E", "F", "G", "H", "I",
  366.            "J", "K", "L", "M", "N", "O", "P", "Q", "R",
  367.            "S", "T", "U", "V", "W", "X", "Y", "Z"
  368.            }
  369.  
  370.        Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask))
  371.  
  372.        For X As Integer = 0 To DeviceID.Length
  373.  
  374.            If DeviceID(X) Then
  375.                Return DriveLetters(X)
  376.            End If
  377.  
  378.        Next X
  379.  
  380.        Return Nothing
  381.  
  382.    End Function
  383.  
  384. #End Region
  385.  
  386. #Region " WndProc"
  387.  
  388.    ''' <summary>
  389.    ''' Invokes the default window procedure associated with this window to process messages for this Window.
  390.    ''' </summary>
  391.    ''' <param name="m">
  392.    ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message.
  393.    ''' </param>
  394.    Protected Overrides Sub WndProc(ByRef m As Message)
  395.  
  396.        Select Case m.Msg
  397.  
  398.            Case DeviceEvents.Change ' The hardware has changed.
  399.  
  400.                ' Transform the LParam pointer into the data structure.
  401.                Dim CurrentWDrive As DEV_BROADCAST_VOLUME =
  402.                    CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME)
  403.  
  404.                Select Case m.WParam.ToInt32
  405.  
  406.                    Case DeviceEvents.Arrival ' The device is connected.
  407.  
  408.                        ' Get the drive letter of the connected device.
  409.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  410.  
  411.                        ' Get the drive information of the connected device.
  412.                        CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
  413.  
  414.                        ' If it's an storage device then...
  415.                        If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then
  416.  
  417.                            ' Inform that the device is connected by raising the 'DriveConnected' event.
  418.                            RaiseEvent DriveInserted(Me, CurrentDrive)
  419.  
  420.                            ' Add the connected device to the dictionary, to retrieve info.
  421.                            If Not CurrentDrives.ContainsKey(DriveLetter) Then
  422.  
  423.                                CurrentDrives.Add(DriveLetter, CurrentDrive)
  424.  
  425.                            End If ' Not CurrentDrives.ContainsKey(DriveLetter)
  426.  
  427.                        End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume
  428.  
  429.                    Case DeviceEvents.QueryRemove ' The device is preparing to be removed.
  430.  
  431.                        ' Get the letter of the current device being removed.
  432.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  433.  
  434.                        ' If the current device being removed is not in the dictionary then...
  435.                        If Not CurrentDrives.ContainsKey(DriveLetter) Then
  436.  
  437.                            ' Get the device information of the current device being removed.
  438.                            CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter))
  439.  
  440.                            ' Add the current device to the dictionary,
  441.                            ' to retrieve info before lost it after fully-removal.
  442.                            CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter)))
  443.  
  444.                        End If ' Not CurrentDrives.ContainsKey(DriveLetter)
  445.  
  446.                    Case DeviceEvents.RemoveComplete
  447.  
  448.                        ' Get the letter of the removed device.
  449.                        DriveLetter = GetDriveLetter(CurrentWDrive)
  450.  
  451.                        ' Inform that the device is disconnected by raising the 'DriveDisconnected' event.
  452.                        RaiseEvent DriveRemoved(Me, CurrentDrive)
  453.  
  454.                        ' If the removed device is in the dictionary then...
  455.                        If CurrentDrives.ContainsKey(DriveLetter) Then
  456.  
  457.                            ' Remove the device from the dictionary.
  458.                            CurrentDrives.Remove(DriveLetter)
  459.  
  460.                        End If ' CurrentDrives.ContainsKey(DriveLetter)
  461.  
  462.                End Select ' m.WParam.ToInt32
  463.  
  464.        End Select ' m.Msg
  465.  
  466.        MyBase.WndProc(m) ' Return Message to base message handler.
  467.  
  468.    End Sub
  469.  
  470. #End Region
  471.  
  472. #Region " Hidden methods "
  473.  
  474.    ' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods.
  475.    ' NOTE: The methods can be re-enabled at any-time if needed.
  476.  
  477.    ''' <summary>
  478.    ''' Assigns a handle to this window.
  479.    ''' </summary>
  480.    <EditorBrowsable(EditorBrowsableState.Never)>
  481.    Public Shadows Sub AssignHandle()
  482.    End Sub
  483.  
  484.    ''' <summary>
  485.    ''' Creates a window and its handle with the specified creation parameters.
  486.    ''' </summary>
  487.    <EditorBrowsable(EditorBrowsableState.Never)>
  488.    Public Shadows Sub CreateHandle()
  489.    End Sub
  490.  
  491.    ''' <summary>
  492.    ''' Creates an object that contains all the relevant information required
  493.    ''' to generate a proxy used to communicate with a remote object.
  494.    ''' </summary>
  495.    <EditorBrowsable(EditorBrowsableState.Never)>
  496.    Public Shadows Sub CreateObjRef()
  497.    End Sub
  498.  
  499.    ''' <summary>
  500.    ''' Invokes the default window procedure associated with this window.
  501.    ''' </summary>
  502.    <EditorBrowsable(EditorBrowsableState.Never)>
  503.    Public Shadows Sub DefWndProc()
  504.    End Sub
  505.  
  506.    ''' <summary>
  507.    ''' Destroys the window and its handle.
  508.    ''' </summary>
  509.    <EditorBrowsable(EditorBrowsableState.Never)>
  510.    Public Shadows Sub DestroyHandle()
  511.    End Sub
  512.  
  513.    ''' <summary>
  514.    ''' Determines whether the specified object is equal to the current object.
  515.    ''' </summary>
  516.    <EditorBrowsable(EditorBrowsableState.Never)>
  517.    Public Shadows Sub Equals()
  518.    End Sub
  519.  
  520.    ''' <summary>
  521.    ''' Serves as the default hash function.
  522.    ''' </summary>
  523.    <EditorBrowsable(EditorBrowsableState.Never)>
  524.    Public Shadows Sub GetHashCode()
  525.    End Sub
  526.  
  527.    ''' <summary>
  528.    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
  529.    ''' </summary>
  530.    <EditorBrowsable(EditorBrowsableState.Never)>
  531.    Public Shadows Sub GetLifetimeService()
  532.    End Sub
  533.  
  534.    ''' <summary>
  535.    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
  536.    ''' </summary>
  537.    <EditorBrowsable(EditorBrowsableState.Never)>
  538.    Public Shadows Sub InitializeLifetimeService()
  539.    End Sub
  540.  
  541.    ''' <summary>
  542.    ''' Releases the handle associated with this window.
  543.    ''' </summary>
  544.    <EditorBrowsable(EditorBrowsableState.Never)>
  545.    Public Shadows Sub ReleaseHandle()
  546.    End Sub
  547.  
  548.    ''' <summary>
  549.    ''' Gets the handle for this window.
  550.    ''' </summary>
  551.    <EditorBrowsable(EditorBrowsableState.Never)>
  552.    Public Shadows Property Handle()
  553.  
  554. #End Region
  555.  
  556. #Region " IDisposable "
  557.  
  558.    ''' <summary>
  559.    ''' To detect redundant calls when disposing.
  560.    ''' </summary>
  561.    Private IsDisposed As Boolean = False
  562.  
  563.    ''' <summary>
  564.    ''' Prevent calls to methods after disposing.
  565.    ''' </summary>
  566.    ''' <exception cref="System.ObjectDisposedException"></exception>
  567.    Private Sub DisposedCheck()
  568.        If Me.IsDisposed Then
  569.            Throw New ObjectDisposedException(Me.GetType().FullName)
  570.        End If
  571.    End Sub
  572.  
  573.    ''' <summary>
  574.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  575.    ''' </summary>
  576.    Public Sub Dispose() Implements IDisposable.Dispose
  577.        Dispose(True)
  578.        GC.SuppressFinalize(Me)
  579.    End Sub
  580.  
  581.    ''' <summary>
  582.    ''' Releases unmanaged and - optionally - managed resources.
  583.    ''' </summary>
  584.    ''' <param name="IsDisposing">
  585.    ''' <c>true</c> to release both managed and unmanaged resources;
  586.    ''' <c>false</c> to release only unmanaged resources.
  587.    ''' </param>
  588.  
  589.    Protected Sub Dispose(ByVal IsDisposing As Boolean)
  590.  
  591.        If Not Me.IsDisposed Then
  592.  
  593.            If IsDisposing Then
  594.                Me.form = Nothing
  595.                MyBase.ReleaseHandle()
  596.                MyBase.DestroyHandle()
  597.            End If
  598.  
  599.        End If
  600.  
  601.        Me.IsDisposed = True
  602.  
  603.    End Sub
  604.  
  605. #End Region
  606.  
  607. End Class

Saludos.
Páginas: 1 ... 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 [758] 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 ... 1254
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines