|
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. ' *********************************************************************** ' Author : Elektro ' Modified : 02-20-2014 ' *********************************************************************** ' <copyright file="DocumentConverter.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Example Usages " ' ' HTML 2 RTF ' RichTextBox1.Rtf = HTMLConverter.Html2Rtf(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default), ' SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False, ' DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst, ' "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined, ' DocumentConverter.PageOrientation.Auto, "Header", "Footer", ' SautinSoft.HtmlToRtf.eImageCompatible.WordPad) ' ' HTML 2 TXT ' RichTextBox1.Text = HTMLConverter.Html2Txt(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default), ' SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False, ' DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst, ' "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined, ' DocumentConverter.PageOrientation.Auto, "Header", "Footer", ' SautinSoft.HtmlToRtf.eImageCompatible.WordPad) ' ' HTML 2 DOC ' Dim MSDocText As String = HTMLConverter.Html2Doc(IO.File.ReadAllText("C:\File.htm", System.Text.Encoding.Default), ' SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False, ' DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst, ' "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined, ' DocumentConverter.PageOrientation.Auto, "Header", "Footer", ' SautinSoft.HtmlToRtf.eImageCompatible.MSWord) ' IO.File.WriteAllText("C:\DocFile.doc", MSDocText, System.Text.Encoding.Default) ' ' TXT 2 RTF ' RichTextBox1.Rtf = DocumentConverter.Txt2Rtf("Hello World!", ' SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False, ' DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst, ' "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined, ' DocumentConverter.PageOrientation.Auto, "Header", "Footer", ' SautinSoft.HtmlToRtf.eImageCompatible.WordPad) ' ' TXT 2 DOC ' Dim MSDocText As String = DocumentConverter.Txt2Doc("Hello World!", ' SautinSoft.HtmlToRtf.eEncoding.AutoDetect, False, ' DocumentConverter.PageSize.Auto, SautinSoft.HtmlToRtf.ePageNumbers.PageNumFirst, ' "Page {page} of {numpages}", SautinSoft.HtmlToRtf.eAlign.Undefined, ' DocumentConverter.PageOrientation.Auto, "Header", "Footer", ' SautinSoft.HtmlToRtf.eImageCompatible.WordPad) ' IO.File.WriteAllText("C:\DocFile.doc", MSDocText, System.Text.Encoding.Default) ' ' RTF 2 HTML ' Dim HTMLString As String = ' DocumentConverter.Rtf2Html(IO.File.ReadAllText("C:\File.rtf"), ' SautinSoft.RtfToHtml.eOutputFormat.XHTML_10, ' SautinSoft.RtfToHtml.eEncoding.UTF_8, ' True, "C:\") ' ' IO.File.WriteAllText("C:\File.html", HTMLString) ' Process.Start("C:\File.html") #End Region #Region " Imports " Imports SautinSoft Imports System.Reflection #End Region ''' <summary> ''' Performs HTML document convertions to other document formats. ''' </summary> Public Class DocumentConverter #Region " Enumerations " ''' <summary> ''' Indicates the resulting PageSize. ''' </summary> Public Enum PageSize Auto A3 A4 A5 A6 B5Iso B5Jis B6 Executive Folio Legal Letter Oficio2 Statement End Enum ''' <summary> ''' Indicates the resulting PageOrientation. ''' </summary> Public Enum PageOrientation Auto Landscape Portrait End Enum #End Region #Region " Private Methods " ''' <summary> ''' Converts a document using 'SautinSoft.HtmlToRtf' library. ''' </summary> ''' <param name="Text"> ''' Indicates the text to convert. ''' </param> ''' <param name="OutputFormat"> ''' Indicates the output document format. ''' </param> ''' <param name="TextEncoding"> ''' Indicates the text encoding. ''' </param> ''' <param name="PreservePageBreaks"> ''' If set to <c>true</c> page breaks are preserved on the conversion. ''' </param> ''' <param name="PageSize"> ''' Indicates the page size. ''' </param> ''' <param name="Pagenumbers"> ''' Indicates the page numbers. ''' </param> ''' <param name="PagenumbersFormat"> ''' Indicates the page numbers format. ''' </param> ''' <param name="PageAlignment"> ''' Indicates the page alignment. ''' </param> ''' <param name="PageOrientation"> ''' Indicates the page orientation. ''' </param> ''' <param name="PageHeader"> ''' Indicates the page header text. ''' </param> ''' <param name="PageFooter"> ''' Indicates the page footer text. ''' </param> ''' <param name="ImageCompatibility"> ''' Indicates the image compatibility if the document contains images. ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images. ''' Microsoft Word can show images in jpeg, png, etc. ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF. ''' </param> ''' <returns>System.String.</returns> Private Shared Function HtmlToRtfConvert(ByVal [Text] As String, ByVal InputFormat As HtmlToRtf.eInputFormat, ByVal OutputFormat As HtmlToRtf.eOutputFormat, Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect, Optional ByVal PreservePageBreaks As Boolean = False, Optional ByVal PageSize As PageSize = PageSize.Auto, Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst, Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}", Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined, Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto, Optional ByVal PageHeader As String = Nothing, Optional ByVal PageFooter As String = Nothing, Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad) As String ' Set the PageSize. Dim PerformPageSize As New HtmlToRtf.CPageStyle.CPageSize() Dim PageSizeMethod As MethodInfo = PerformPageSize.GetType().GetMethod(PageSize.ToString()) ' Set the PageOrientation. Dim PerformPageOrientation As New HtmlToRtf.CPageStyle.CPageOrientation Dim PageOrientationMethod As MethodInfo = PerformPageOrientation.GetType().GetMethod(PageOrientation.ToString()) ' Call the PageSize method. If Not PageSizeMethod Is Nothing Then PageSizeMethod.Invoke(PerformPageSize, Nothing) Else Throw New Exception(String.Format("PageSize method {0} not found.", PageSize.ToString)) End If ' Call the PageOrientation method. If Not PageOrientationMethod Is Nothing Then PageOrientationMethod.Invoke(PerformPageOrientation, Nothing) Else Throw New Exception(String.Format("PageOrientation method {0} not found.", PageOrientation.ToString)) End If ' Instance a new document converter. Dim Converter As New HtmlToRtf ' Customize the conversion options. With Converter .Serial = "123456789012" .InputFormat = InputFormat .OutputFormat = OutputFormat .Encoding = TextEncoding .PreservePageBreaks = PreservePageBreaks .ImageCompatible = ImageCompatibility .PageAlignment = PageAlignment .PageNumbers = Pagenumbers .PageNumbersFormat = PagenumbersFormat .PageStyle.PageSize = PerformPageSize .PageStyle.PageOrientation = PerformPageOrientation If Not String.IsNullOrEmpty(PageHeader) Then .PageStyle.PageHeader.Text(PageHeader) If Not String.IsNullOrEmpty(PageFooter) Then .PageStyle.PageFooter.Text(PageFooter) End With ' Convert it. Return Converter.ConvertString([Text]) End Function ''' <summary> ''' Converts a document using 'SautinSoft.RtfToHtml' library. ''' </summary> ''' <param name="Text"> ''' Indicates the text to convert. ''' </param> ''' <param name="OutputFormat"> ''' Indicates the output HTML format. ''' </param> ''' <param name="TextEncoding"> ''' Indicates the text encoding. ''' </param> ''' <param name="SaveImagesToDisk"> ''' If set to <c>true</c>, converted images are saved to a directory on hard drive. ''' </param> ''' <param name="ImageFolder"> ''' If 'SaveImagesToDisk' parameter is set to 'True', indicates the image directory to save the images. ''' The directory must exist. ''' </param> ''' <returns>System.String.</returns> Private Shared Function RtfToHtmlConvert(ByVal [Text] As String, Optional ByVal OutputFormat As RtfToHtml.eOutputFormat = RtfToHtml.eOutputFormat.XHTML_10, Optional ByVal TextEncoding As RtfToHtml.eEncoding = RtfToHtml.eEncoding.UTF_8, Optional ByVal SaveImagesToDisk As Boolean = False, Optional ByVal ImageFolder As String = "C:\") As String ' Instance a new document converter. Dim Converter As New RtfToHtml ' Customize the conversion options. With Converter .Serial = "123456789012" .OutputFormat = OutputFormat .Encoding = TextEncoding .ImageStyle.IncludeImageInHtml = Not SaveImagesToDisk .ImageStyle.ImageFolder = ImageFolder ' This folder must exist to save the converted images. .ImageStyle.ImageSubFolder = "Pictures" ' This subfolder will be created by the component to save the images. .ImageStyle.ImageFileName = "picture" ' Pattern name for converted images. (Ex: 'Picture1.png') End With ' Convert it. Return Converter.ConvertString([Text]) End Function #End Region #Region " Public Methods " ''' <summary> ''' Converts HTML text to DOC (Microsoft Word). ''' </summary> ''' <param name="HtmlText"> ''' Indicates the HTML text to convert. ''' </param> ''' <param name="TextEncoding"> ''' Indicates the text encoding. ''' </param> ''' <param name="PreservePageBreaks"> ''' If set to <c>true</c> page breaks are preserved on the conversion. ''' </param> ''' <param name="PageSize"> ''' Indicates the page size. ''' </param> ''' <param name="Pagenumbers"> ''' Indicates the page numbers. ''' </param> ''' <param name="PagenumbersFormat"> ''' Indicates the page numbers format. ''' </param> ''' <param name="PageAlignment"> ''' Indicates the page alignment. ''' </param> ''' <param name="PageOrientation"> ''' Indicates the page orientation. ''' </param> ''' <param name="PageHeader"> ''' Indicates the page header text. ''' </param> ''' <param name="PageFooter"> ''' Indicates the page footer text. ''' </param> ''' <param name="ImageCompatibility"> ''' Indicates the image compatibility if the document contains images. ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images. ''' Microsoft Word can show images in jpeg, png, etc. ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF. ''' </param> ''' <returns>System.String.</returns> Public Shared Function Html2Doc(ByVal HtmlText As String, Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect, Optional ByVal PreservePageBreaks As Boolean = False, Optional ByVal PageSize As PageSize = PageSize.Auto, Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst, Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}", Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined, Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto, Optional ByVal PageHeader As String = Nothing, Optional ByVal PageFooter As String = Nothing, Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad ) As String Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.Doc, TextEncoding, PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat, PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility) End Function ''' <summary> ''' Converts HTML text to RTF (Rich Text). ''' </summary> ''' <param name="HtmlText"> ''' Indicates the HTML text to convert. ''' </param> ''' <param name="TextEncoding"> ''' Indicates the text encoding. ''' </param> ''' <param name="PreservePageBreaks"> ''' If set to <c>true</c> page breaks are preserved on the conversion. ''' </param> ''' <param name="PageSize"> ''' Indicates the page size. ''' </param> ''' <param name="Pagenumbers"> ''' Indicates the page numbers. ''' </param> ''' <param name="PagenumbersFormat"> ''' Indicates the page numbers format. ''' </param> ''' <param name="PageAlignment"> ''' Indicates the page alignment. ''' </param> ''' <param name="PageOrientation"> ''' Indicates the page orientation. ''' </param> ''' <param name="PageHeader"> ''' Indicates the page header text. ''' </param> ''' <param name="PageFooter"> ''' Indicates the page footer text. ''' </param> ''' <param name="ImageCompatibility"> ''' Indicates the image compatibility if the document contains images. ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images. ''' Microsoft Word can show images in jpeg, png, etc. ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF. ''' </param> ''' <returns>System.String.</returns> Public Shared Function Html2Rtf(ByVal HtmlText As String, Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect, Optional ByVal PreservePageBreaks As Boolean = False, Optional ByVal PageSize As PageSize = PageSize.Auto, Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst, Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}", Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined, Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto, Optional ByVal PageHeader As String = Nothing, Optional ByVal PageFooter As String = Nothing, Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad ) As String Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.Rtf, TextEncoding, PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat, PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility) End Function ''' <summary> ''' Converts HTML text to TXT (Plain Text). ''' </summary> ''' <param name="HtmlText"> ''' Indicates the HTML text to convert. ''' </param> ''' <param name="TextEncoding"> ''' Indicates the text encoding. ''' </param> ''' <param name="PreservePageBreaks"> ''' If set to <c>true</c> page breaks are preserved on the conversion. ''' </param> ''' <param name="PageSize"> ''' Indicates the page size. ''' </param> ''' <param name="Pagenumbers"> ''' Indicates the page numbers. ''' </param> ''' <param name="PagenumbersFormat"> ''' Indicates the page numbers format. ''' </param> ''' <param name="PageAlignment"> ''' Indicates the page alignment. ''' </param> ''' <param name="PageOrientation"> ''' Indicates the page orientation. ''' </param> ''' <param name="PageHeader"> ''' Indicates the page header text. ''' </param> ''' <param name="PageFooter"> ''' Indicates the page footer text. ''' </param> ''' <param name="ImageCompatibility"> ''' Indicates the image compatibility if the document contains images. ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images. ''' Microsoft Word can show images in jpeg, png, etc. ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF. ''' </param> ''' <returns>System.String.</returns> Public Shared Function Html2Txt(ByVal HtmlText As String, Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect, Optional ByVal PreservePageBreaks As Boolean = False, Optional ByVal PageSize As PageSize = PageSize.Auto, Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst, Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}", Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined, Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto, Optional ByVal PageHeader As String = Nothing, Optional ByVal PageFooter As String = Nothing, Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad ) As String Return HtmlToRtfConvert(HtmlText, HtmlToRtf.eInputFormat.Html, HtmlToRtf.eOutputFormat.TextAnsi, TextEncoding, PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat, PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility) End Function ''' <summary> ''' Converts TXT to DOC (Microsoft Word). ''' </summary> ''' <param name="Text"> ''' Indicates the plain text to convert. ''' </param> ''' <param name="TextEncoding"> ''' Indicates the text encoding. ''' </param> ''' <param name="PreservePageBreaks"> ''' If set to <c>true</c> page breaks are preserved on the conversion. ''' </param> ''' <param name="PageSize"> ''' Indicates the page size. ''' </param> ''' <param name="Pagenumbers"> ''' Indicates the page numbers. ''' </param> ''' <param name="PagenumbersFormat"> ''' Indicates the page numbers format. ''' </param> ''' <param name="PageAlignment"> ''' Indicates the page alignment. ''' </param> ''' <param name="PageOrientation"> ''' Indicates the page orientation. ''' </param> ''' <param name="PageHeader"> ''' Indicates the page header text. ''' </param> ''' <param name="PageFooter"> ''' Indicates the page footer text. ''' </param> ''' <param name="ImageCompatibility"> ''' Indicates the image compatibility if the document contains images. ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images. ''' Microsoft Word can show images in jpeg, png, etc. ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF. ''' </param> ''' <returns>System.String.</returns> Public Shared Function Txt2Doc(ByVal [Text] As String, Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect, Optional ByVal PreservePageBreaks As Boolean = False, Optional ByVal PageSize As PageSize = PageSize.Auto, Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst, Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}", Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined, Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto, Optional ByVal PageHeader As String = Nothing, Optional ByVal PageFooter As String = Nothing, Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad ) As String Return HtmlToRtfConvert([Text], HtmlToRtf.eInputFormat.Text, HtmlToRtf.eOutputFormat.Doc, TextEncoding, PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat, PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility) End Function ''' <summary> ''' Converts TXT to RTF (Rich Text). ''' </summary> ''' <param name="Text"> ''' Indicates the plain text to convert. ''' </param> ''' <param name="TextEncoding"> ''' Indicates the text encoding. ''' </param> ''' <param name="PreservePageBreaks"> ''' If set to <c>true</c> page breaks are preserved on the conversion. ''' </param> ''' <param name="PageSize"> ''' Indicates the page size. ''' </param> ''' <param name="Pagenumbers"> ''' Indicates the page numbers. ''' </param> ''' <param name="PagenumbersFormat"> ''' Indicates the page numbers format. ''' </param> ''' <param name="PageAlignment"> ''' Indicates the page alignment. ''' </param> ''' <param name="PageOrientation"> ''' Indicates the page orientation. ''' </param> ''' <param name="PageHeader"> ''' Indicates the page header text. ''' </param> ''' <param name="PageFooter"> ''' Indicates the page footer text. ''' </param> ''' <param name="ImageCompatibility"> ''' Indicates the image compatibility if the document contains images. ''' RichTexBox control and WordPad can't show jpeg and png images inside RTF, they can show only bitmap images. ''' Microsoft Word can show images in jpeg, png, etc. ''' If this property is set to 'eImageCompatible.WordPad' images will be stored as BMP inside RTF. ''' </param> ''' <returns>System.String.</returns> Public Shared Function Txt2Rtf(ByVal [Text] As String, Optional ByVal TextEncoding As HtmlToRtf.eEncoding = HtmlToRtf.eEncoding.AutoDetect, Optional ByVal PreservePageBreaks As Boolean = False, Optional ByVal PageSize As PageSize = PageSize.Auto, Optional ByVal Pagenumbers As HtmlToRtf.ePageNumbers = HtmlToRtf.ePageNumbers.PageNumFirst, Optional ByVal PagenumbersFormat As String = "Page {page} of {numpages}", Optional ByVal PageAlignment As HtmlToRtf.eAlign = HtmlToRtf.eAlign.Undefined, Optional ByVal PageOrientation As PageOrientation = PageOrientation.Auto, Optional ByVal PageHeader As String = Nothing, Optional ByVal PageFooter As String = Nothing, Optional ByVal ImageCompatibility As HtmlToRtf.eImageCompatible = HtmlToRtf.eImageCompatible.WordPad ) As String Return HtmlToRtfConvert([Text], HtmlToRtf.eInputFormat.Text, HtmlToRtf.eOutputFormat.Rtf, TextEncoding, PreservePageBreaks, PageSize, Pagenumbers, PagenumbersFormat, PageAlignment, PageOrientation, PageHeader, PageFooter, ImageCompatibility) End Function ''' <summary> ''' Converts RtF to HtML. ''' </summary> ''' <param name="RtfText"> ''' Indicates the rich text to convert. ''' </param> ''' <param name="OutputFormat"> ''' Indicates the output HTML format. ''' </param> ''' <param name="TextEncoding"> ''' Indicates the text encoding. ''' </param> ''' <param name="SaveImagesToDisk"> ''' If set to <c>true</c>, converted images are saved to a directory on hard drive. ''' </param> ''' <param name="ImageFolder"> ''' If 'SaveImagesToDisk' parameter is set to 'True', indicates the image directory to save the images. ''' The directory must exist. ''' </param> ''' <returns>System.String.</returns> Public Shared Function Rtf2Html(ByVal RtfText As String, Optional ByVal OutputFormat As RtfToHtml.eOutputFormat = RtfToHtml.eOutputFormat.XHTML_10, Optional ByVal TextEncoding As RtfToHtml.eEncoding = RtfToHtml.eEncoding.UTF_8, Optional ByVal SaveImagesToDisk As Boolean = False, Optional ByVal ImageFolder As String = "C:\") As String Return RtfToHtmlConvert(RtFText, OutputFormat, TextEncoding, SaveImagesToDisk, ImageFolder) End Function #End Region 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. ' Colorize Words ' ( By Elektro ) ' ' Usage Examples: ' ' ColorizeWord(RichTextBox1, "Hello", True, ' Color.Red, Color.Black, ' New Font(RichTextBox1.Font.FontFamily, RichTextBox1.Font.Size, FontStyle.Italic)) ' ' ColorizeWords(RichTextBox1, {"Hello", "[0-9]"}, IgnoreCase:=False, ' ForeColor:=Color.Red, BackColor:=Nothing, Font:=Nothing) ''' <summary> ''' Find a word on a RichTextBox and colorizes each match. ''' </summary> ''' <param name="RichTextBox">Indicates the RichTextBox.</param> ''' <param name="Word">Indicates the word to colorize.</param> ''' <param name="IgnoreCase">Indicates the ignore case.</param> ''' <param name="ForeColor">Indicates the text color.</param> ''' <param name="BackColor">Indicates the background color.</param> ''' <param name="Font">Indicates the text font.</param> ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns> Private Function ColorizeWord(ByVal [RichTextBox] As RichTextBox, ByVal Word As String, Optional ByVal IgnoreCase As Boolean = False, Optional ByVal ForeColor As Color = Nothing, Optional ByVal BackColor As Color = Nothing, Optional ByVal [Font] As Font = Nothing) As Boolean ' Find all the word matches. Dim Matches As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches([RichTextBox].Text, Word, If(IgnoreCase, System.Text.RegularExpressions.RegexOptions.IgnoreCase, System.Text.RegularExpressions.RegexOptions.None)) ' If no matches then return. If Not Matches.Count <> 0 Then Return False End If ' Set the passed Parameter values. If ForeColor.Equals(Nothing) Then ForeColor = [RichTextBox].ForeColor If BackColor.Equals(Nothing) Then BackColor = [RichTextBox].BackColor If [Font] Is Nothing Then [Font] = [RichTextBox].Font ' Store the current caret position to restore it at the end. Dim CaretPosition As Integer = [RichTextBox].SelectionStart ' Suspend the control layout to work quicklly. [RichTextBox].SuspendLayout() ' Colorize each match. For Each Match As System.Text.RegularExpressions.Match In Matches [RichTextBox].Select(Match.Index, Match.Length) [RichTextBox].SelectionColor = ForeColor [RichTextBox].SelectionBackColor = BackColor [RichTextBox].SelectionFont = [Font] Next Match ' Restore the caret position. [RichTextBox].Select(CaretPosition, 0) ' Restore the control layout. [RichTextBox].ResumeLayout() ' Return successfully Return True End Function ''' <summary> ''' Find multiple words on a RichTextBox and colorizes each match. ''' </summary> ''' <param name="RichTextBox">Indicates the RichTextBox.</param> ''' <param name="Words">Indicates the words to colorize.</param> ''' <param name="IgnoreCase">Indicates the ignore case.</param> ''' <param name="ForeColor">Indicates the text color.</param> ''' <param name="BackColor">Indicates the background color.</param> ''' <param name="Font">Indicates the text font.</param> ''' <returns><c>true</c> if matched at least one word, <c>false</c> otherwise.</returns> Private Function ColorizeWords(ByVal [RichTextBox] As RichTextBox, ByVal Words As String(), Optional ByVal IgnoreCase As Boolean = False, Optional ByVal ForeColor As Color = Nothing, Optional ByVal BackColor As Color = Nothing, Optional ByVal [Font] As Font = Nothing) As Boolean Dim Success As Boolean = False For Each Word As String In Words Success += ColorizeWord([RichTextBox], Word, IgnoreCase, ForeColor, BackColor, [Font]) Next Word Return Success End Function
[ListView] Remove Duplicates Elimina Items duplicados de un Listview, comparando un índice de subitem específico. ' Remove ListView Duplicates ' ( By Elektro ) ' ' Usage Examples: ' Dim Items As ListView.ListViewItemCollection = New ListView.ListViewItemCollection(ListView1) ' RemoveListViewDuplicates(Items, 0) ' ''' <summary> ''' Removes duplicated items from a Listview. ''' </summary> ''' <param name="Items"> ''' Indicates the items collection. ''' </param> ''' <param name="SubitemCompare"> ''' Indicates the subitem column to compare duplicates. ''' </param> Private Sub RemoveListViewDuplicates(ByVal Items As ListView.ListViewItemCollection, ByVal SubitemCompare As Integer) ' Suspend the layout on the Control that owns the Items collection. Items.Item(0).ListView.SuspendLayout() ' Get the duplicated Items. Dim Duplicates As ListViewItem() = Items.Cast(Of ListViewItem)(). GroupBy(Function(Item As ListViewItem) Item.SubItems(SubitemCompare).Text). Where(Function(g As IGrouping(Of String, ListViewItem)) g.Count <> 1). SelectMany(Function(g As IGrouping(Of String, ListViewItem)) g). Skip(1). ToArray() ' Delete the duplicated Items. For Each Item As ListViewItem In Duplicates Items.Remove(Item) Next Item ' Resume the layout on the Control that owns the Items collection. Items.Item(0).ListView.ResumeLayout() Duplicates = Nothing End Sub
Formatea un dispositivo ' Format Drive ' ( By Elektro ) ' ' Usage Examples: ' FormatDrive("Z") ' MsgBox(FormatDrive("Z", DriveFileSystem.NTFS, True, 4096, "Formatted", False)) ''' <summary> ''' Indicates the possible HardDisk filesystem's for Windows OS. ''' </summary> Public Enum DriveFileSystem As Integer ' NOTE: ' ***** ' The numeric values just indicates the max harddisk volume-label character-length for each filesystem. ''' <summary> ''' NTFS FileSystem. ''' </summary> NTFS = 32 ''' <summary> ''' FAT16 FileSystem. ''' </summary> FAT16 = 11 ''' <summary> ''' FAT32 FileSystem. ''' </summary> FAT32 = FAT16 End Enum ''' <summary> ''' Formats a drive. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/aa390432%28v=vs.85%29.aspx ''' </summary> ''' <param name="DriveLetter"> ''' Indicates the drive letter to format. ''' </param> ''' <param name="FileSystem"> ''' Indicates the filesystem format to use for this volume. ''' The default is "NTFS". ''' </param> ''' <param name="QuickFormat"> ''' If set to <c>true</c>, formats the volume with a quick format by removing files from the disk ''' without scanning the disk for bad sectors. ''' Use this option only if the disk has been previously formatted, ''' and you know that the disk is not damaged. ''' The default is <c>true</c>. ''' </param> ''' <param name="ClusterSize"> ''' Disk allocation unit size—cluster size. ''' All of the filesystems organizes the hard disk based on cluster size, ''' which represents the smallest amount of disk space that can be allocated to hold a file. ''' The smaller the cluster size you use, the more efficiently your disk stores information. ''' If no cluster size is specified during format, Windows picks defaults based on the size of the volume. ''' These defaults have been selected to reduce the amount of space lost and to reduce fragmentation. ''' For general use, the default settings are strongly recommended. ''' </param> ''' <param name="VolumeLabel"> ''' Indicates the Label to use for the new volume. ''' The volume label can contain up to 11 characters for FAT16 and FAT32 volumes, ''' and up to 32 characters for NTFS filesystem volumes. ''' </param> ''' <param name="EnableCompression">Not implemented.</param> ''' <returns> ''' 0 = Success. ''' 1 = Unsupported file system. ''' 2 = Incompatible media in drive. ''' 3 = Access denied. ''' 4 = Call canceled. ''' 5 = Call cancellation request too late. ''' 6 = Volume write protected. ''' 7 = Volume lock failed. ''' 8 = Unable to quick format. ''' 9 = Input/Output (I/O) error. ''' 10 = Invalid volume label. ''' 11 = No media in drive. ''' 12 = Volume is too small. ''' 13 = Volume is too large. ''' 14 = Volume is not mounted. ''' 15 = Cluster size is too small. ''' 16 = Cluster size is too large. ''' 17 = Cluster size is beyond 32 bits. ''' 18 = Unknown error. ''' </returns> Public Function FormatDrive(ByVal DriveLetter As Char, Optional ByVal FileSystem As DriveFileSystem = DriveFileSystem.NTFS, Optional ByVal QuickFormat As Boolean = True, Optional ByVal ClusterSize As Integer = Nothing, Optional ByVal VolumeLabel As String = Nothing, Optional ByVal EnableCompression As Boolean = False) As Integer ' Volume-label error check. If Not String.IsNullOrEmpty(VolumeLabel) Then If VolumeLabel.Length > FileSystem Then Throw New Exception(String.Format("Volume label for '{0}' filesystem can't be larger than '{1}' characters.", FileSystem.ToString, CStr(FileSystem))) End If End If Dim Query As String = String.Format("select * from Win32_Volume WHERE DriveLetter = '{0}:'", Convert.ToString(DriveLetter)) Using WMI As New ManagementObjectSearcher(Query) Return CInt(WMI.[Get].Cast(Of ManagementObject).First. InvokeMethod("Format", New Object() {FileSystem, QuickFormat, ClusterSize, VolumeLabel, EnableCompression})) End Using Return 18 ' Unknown error. End Function
|
|
|
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): Set "Output= %HomeDrive%\Registros\Cliente.reg" Set "Key=HKCU\Software\SimonTatham\PuTTY\Sessions\CIA %%20- %%20Cliente" Reg Export "%Key%" "%Output%"
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 SendInputHe 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: Private Sub Test() Handles Button1.Click AppActivate(Process.GetProcessesByName("notepad").First.Id) Dim Result As Integer = SendInputs.SendKeys(Keys.Insert, BlockInput:=False) ' Dim Result2 As Integer = SendInputs.SendKey(Convert.ToChar(Keys.Enter)) ' Dim Result2 As Integer = SendInputs.SendKey("x"c) MessageBox.Show(String.Format("Successfull events: {0}", CStr(Result))) #End If End Sub
' *********************************************************************** ' Author : Elektro ' Modified : 02-17-2014 ' *********************************************************************** ' <copyright file="SendInputs.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Imports " Imports System.Runtime.InteropServices Imports System.ComponentModel #End Region ''' <summary> ''' ''' </summary> Public Class SendInputs #Region " P/Invoke " Friend Class NativeMethods #Region " Methods " ''' <summary> ''' Blocks keyboard and mouse input events from reaching applications. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646290%28v=vs.85%29.aspx ''' </summary> ''' <param name="fBlockIt"> ''' The function's purpose. ''' If this parameter is 'TRUE', keyboard and mouse input events are blocked. ''' If this parameter is 'FALSE', keyboard and mouse events are unblocked. ''' </param> ''' <returns> ''' If the function succeeds, the return value is nonzero. ''' If input is already blocked, the return value is zero. ''' </returns> ''' <remarks> ''' Note that only the thread that blocked input can successfully unblock input. ''' </remarks> <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall, SetLastError:=True)> Friend Shared Function BlockInput( ByVal fBlockIt As Boolean ) As Integer End Function ''' <summary> ''' Synthesizes keystrokes, mouse motions, and button clicks. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310%28v=vs.85%29.aspx ''' </summary> ''' <param name="nInputs"> ''' Indicates the number of structures in the pInputs array. ''' </param> ''' <param name="pInputs"> ''' Indicates an Array of 'INPUT' structures. ''' Each structure represents an event to be inserted into the keyboard or mouse input stream. ''' </param> ''' <param name="cbSize"> ''' The size, in bytes, of an 'INPUT' structure. ''' If 'cbSize' is not the size of an 'INPUT' structure, the function fails. ''' </param> ''' <returns> ''' The function returns the number of events that it successfully ''' inserted into the keyboard or mouse input stream. ''' If the function returns zero, the input was already blocked by another thread. ''' </returns> <DllImport("user32.dll", SetLastError:=True)> Friend Shared Function SendInput( ByVal nInputs As Integer, <MarshalAs(UnmanagedType.LPArray), [In]> ByVal pInputs As INPUT(), ByVal cbSize As Integer ) As Integer End Function #End Region #Region " Enumerations " ''' <summary> ''' VirtualKey codes. ''' </summary> Friend Enum VirtualKeys As Short ''' <summary> ''' The Shift key. ''' VK_SHIFT ''' </summary> SHIFT = &H10S ''' <summary> ''' The DEL key. ''' VK_DELETE ''' </summary> DELETE = 46S ''' <summary> ''' The ENTER key. ''' VK_RETURN ''' </summary> [RETURN] = 13S End Enum ''' <summary> ''' The type of the input event. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx ''' </summary> <Description("Enumeration used for 'type' parameter of 'INPUT' structure")> Friend Enum InputType As Integer ''' <summary> ''' The event is a mouse event. ''' Use the mi structure of the union. ''' </summary> Mouse = 0 ''' <summary> ''' The event is a keyboard event. ''' Use the ki structure of the union. ''' </summary> Keyboard = 1 ''' <summary> ''' The event is a hardware event. ''' Use the hi structure of the union. ''' </summary> Hardware = 2 End Enum ''' <summary> ''' Specifies various aspects of a keystroke. ''' This member can be certain combinations of the following values. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx ''' </summary> <Description("Enumeration used for 'dwFlags' parameter of 'KEYBDINPUT ' structure")> <Flags> Friend Enum KeyboardInput_Flags As Integer ''' <summary> ''' If specified, the scan code was preceded by a prefix byte that has the value '0xE0' (224). ''' </summary> ExtendedKey = &H1 ''' <summary> ''' If specified, the key is being pressed. ''' </summary> KeyDown = &H0 ''' <summary> ''' If specified, the key is being released. ''' If not specified, the key is being pressed. ''' </summary> KeyUp = &H2 ''' <summary> ''' If specified, 'wScan' identifies the key and 'wVk' is ignored. ''' </summary> ScanCode = &H8 ''' <summary> ''' If specified, the system synthesizes a 'VK_PACKET' keystroke. ''' The 'wVk' parameter must be '0'. ''' This flag can only be combined with the 'KEYEVENTF_KEYUP' flag. ''' </summary> Unicode = &H4 End Enum #End Region #Region " Structures " ''' <summary> ''' Used by 'SendInput' function ''' to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx ''' </summary> <Description("Structure used for 'INPUT' parameter of 'SendInput' API method")> <StructLayout(LayoutKind.Explicit)> Friend Structure INPUT ' ****** ' NOTE ' ****** ' Field offset for 32 bit machine: 4 ' Field offset for 64 bit machine: 8 ''' <summary> ''' The type of the input event. ''' </summary> <FieldOffset(0)> Public type As InputType ''' <summary> ''' The information about a simulated mouse event. ''' </summary> <FieldOffset(8)> Public mi As MOUSEINPUT ''' <summary> ''' The information about a simulated keyboard event. ''' </summary> <FieldOffset(8)> Public ki As KEYBDINPUT ''' <summary> ''' The information about a simulated hardware event. ''' </summary> <FieldOffset(8)> Public hi As HARDWAREINPUT End Structure ''' <summary> ''' Contains information about a simulated mouse event. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx ''' </summary> <Description("Structure used for 'mi' parameter of 'INPUT' structure")> Friend Structure MOUSEINPUT ''' <summary> ''' ''' </summary> Public dx As Integer ''' <summary> ''' ''' </summary> Public dy As Integer ''' <summary> ''' ''' </summary> Public mouseData As Integer ''' <summary> ''' ''' </summary> Public dwFlags As Integer ''' <summary> ''' ''' </summary> Public time As Integer ''' <summary> ''' ''' </summary> Public dwExtraInfo As IntPtr End Structure ''' <summary> ''' Contains information about a simulated keyboard event. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx ''' </summary> <Description("Structure used for 'ki' parameter of 'INPUT' structure")> Friend Structure KEYBDINPUT ''' <summary> ''' A virtual-key code. ''' The code must be a value in the range '1' to '254'. ''' If the 'dwFlags' member specifies 'KEYEVENTF_UNICODE', wVk must be '0'. ''' </summary> Public wVk As Short ''' <summary> ''' A hardware scan code for the key. ''' If 'dwFlags' specifies 'KEYEVENTF_UNICODE', ''' 'wScan' specifies a Unicode character which is to be sent to the foreground application. ''' </summary> Public wScan As Short ''' <summary> ''' Specifies various aspects of a keystroke. ''' </summary> Public dwFlags As KeyboardInput_Flags ''' <summary> ''' The time stamp for the event, in milliseconds. ''' If this parameter is '0', the system will provide its own time stamp. ''' </summary> Public time As Integer ''' <summary> ''' An additional value associated with the keystroke. ''' Use the 'GetMessageExtraInfo' function to obtain this information. ''' </summary> Public dwExtraInfo As IntPtr End Structure ''' <summary> ''' Contains information about a simulated message generated by an input device other than a keyboard or mouse. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646269%28v=vs.85%29.aspx ''' </summary> <Description("Structure used for 'hi' parameter of 'INPUT' structure")> Friend Structure HARDWAREINPUT ''' <summary> ''' The message generated by the input hardware. ''' </summary> Public uMsg As Integer ''' <summary> ''' The low-order word of the lParam parameter for uMsg. ''' </summary> Public wParamL As Short ''' <summary> ''' The high-order word of the lParam parameter for uMsg. ''' </summary> Public wParamH As Short End Structure #End Region End Class #End Region #Region " Public Methods " ''' <summary> ''' Sends a keystroke. ''' </summary> ''' <param name="key"> ''' Indicates the keystroke to simulate. ''' </param> ''' <param name="BlockInput"> ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent. ''' </param> ''' <returns> ''' The function returns the number of events that it successfully ''' inserted into the keyboard or mouse input stream. ''' If the function returns zero, the input was already blocked by another thread. ''' </returns> Public Shared Function SendKey(ByVal key As Char, Optional BlockInput As Boolean = False) As Integer ' Block Keyboard and mouse. If BlockInput Then NativeMethods.BlockInput(True) ' The inputs structures to send. Dim Inputs As New List(Of NativeMethods.INPUT) ' The current input to add into the Inputs list. Dim CurrentInput As New NativeMethods.INPUT ' Determines whether a character is an alphabetic letter. Dim IsAlphabetic As Boolean = Not (key.ToString.ToUpper = key.ToString.ToLower) ' Determines whether a character is an uppercase alphabetic letter. Dim IsUpperCase As Boolean = (key.ToString = key.ToString.ToUpper) AndAlso Not (key.ToString.ToUpper = key.ToString.ToLower) ' Determines whether the CapsLock key is pressed down. Dim CapsLockON As Boolean = My.Computer.Keyboard.CapsLock ' Set the passed key to upper-case. If IsAlphabetic AndAlso Not IsUpperCase Then key = Convert.ToChar(key.ToString.ToUpper) End If ' If character is UpperCase and CapsLock is pressed down, ' OrElse character is not UpperCase and CapsLock is not pressed down. If (IsAlphabetic AndAlso IsUpperCase AndAlso CapsLockON) _ OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso Not CapsLockON) _ OrElse (Not IsAlphabetic) Then ' Hold the character key. With CurrentInput .type = NativeMethods.InputType.Keyboard .ki.wVk = Convert.ToInt16(CChar(key)) .ki.dwFlags = 0 End With : Inputs.Add(CurrentInput) ' Release the character key. With CurrentInput .type = NativeMethods.InputType.Keyboard .ki.wVk = Convert.ToInt16(CChar(key)) .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp End With : Inputs.Add(CurrentInput) ' If character is UpperCase and CapsLock is not pressed down, ' OrElse character is not UpperCase and CapsLock is pressed down. ElseIf (IsAlphabetic AndAlso IsUpperCase AndAlso Not CapsLockON) _ OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso CapsLockON) Then ' Hold the Shift key. With CurrentInput .type = NativeMethods.InputType.Keyboard .ki.wVk = NativeMethods.VirtualKeys.SHIFT .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown End With : Inputs.Add(CurrentInput) ' Hold the character key. With CurrentInput .type = NativeMethods.InputType.Keyboard .ki.wVk = Convert.ToInt16(CChar(key)) .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown End With : Inputs.Add(CurrentInput) ' Release the character key. With CurrentInput .type = NativeMethods.InputType.Keyboard .ki.wVk = Convert.ToInt16(CChar(key)) .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp End With : Inputs.Add(CurrentInput) ' Release the Shift key. With CurrentInput .type = NativeMethods.InputType.Keyboard .ki.wVk = NativeMethods.VirtualKeys.SHIFT .ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp End With : Inputs.Add(CurrentInput) End If ' UpperCase And My.Computer.Keyboard.CapsLock is... ' Send the input key. Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray, Marshal.SizeOf(GetType(NativeMethods.INPUT))) ' Unblock Keyboard and mouse. If BlockInput Then NativeMethods.BlockInput(False) End Function ''' <summary> ''' Sends a keystroke. ''' </summary> ''' <param name="key"> ''' Indicates the keystroke to simulate. ''' </param> ''' <param name="BlockInput"> ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent. ''' </param> ''' <returns> ''' The function returns the number of events that it successfully ''' inserted into the keyboard or mouse input stream. ''' If the function returns zero, the input was already blocked by another thread. ''' </returns> Public Shared Function SendKey(ByVal key As Keys, Optional BlockInput As Boolean = False) As Integer Return SendKey(Convert.ToChar(key), BlockInput) End Function ''' <summary> ''' Sends a string. ''' </summary> ''' <param name="String"> ''' Indicates the string to send. ''' </param> ''' <param name="BlockInput"> ''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent. ''' </param> ''' <returns> ''' The function returns the number of events that it successfully ''' inserted into the keyboard or mouse input stream. ''' If the function returns zero, the input was already blocked by another thread. ''' </returns> Public Shared Function SendKeys(ByVal [String] As String, Optional BlockInput As Boolean = False) As Integer Dim SuccessCount As Integer = 0 ' Block Keyboard and mouse. If BlockInput Then NativeMethods.BlockInput(True) For Each c As Char In [String] SuccessCount += SendKey(c, BlockInput:=False) Next c ' Unblock Keyboard and mouse. If BlockInput Then NativeMethods.BlockInput(False) Return SuccessCount End Function #End Region 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: 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 ' GetDrivesOfType ' ( By Elektro ) ' ' Usage Examples: ' ' Dim Drives As IO.DriveInfo() = GetDrivesOfType(IO.DriveType.Fixed) ' ' For Each Drive As IO.DriveInfo In GetDrivesOfType(IO.DriveType.Removable) ' MsgBox(Drive.Name) ' Next Drive ' ''' <summary> ''' Get all the connected drives of the given type. ''' </summary> ''' <param name="DriveType">Indicates the type of the drive.</param> ''' <returns>System.IO.DriveInfo[].</returns> Public Function GetDrivesOfType(ByVal DriveType As IO.DriveType) As IO.DriveInfo() Return (From Drive As IO. DriveInfo In IO. DriveInfo. GetDrives Where Drive. DriveType = DriveType ). ToArray End Function
monitorizar la inserción/extracción de dispositivos ' *********************************************************************** ' Author : Elektro ' Modified : 02-17-2014 ' *********************************************************************** ' <copyright file="DriveWatcher.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " ' ''' <summary> ' ''' The DriveWatcher instance to monitor USB devices. ' ''' </summary> 'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me) ' ''' <summary> ' ''' Handles the DriveInserted event of the USBMonitor object. ' ''' </summary> ' ''' <param name="sender">The source of the event.</param> ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> 'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted ' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then... ' Dim sb As New System.Text.StringBuilder ' sb.AppendLine("DRIVE CONNECTED!") ' sb.AppendLine() ' sb.AppendLine(String.Format("Drive Name: {0}", e.Name)) ' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType)) ' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat)) ' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady)) ' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory)) ' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel)) ' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize)) ' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace)) ' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace)) ' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information) ' End If 'End Sub ' ''' <summary> ' ''' Handles the DriveRemoved event of the USBMonitor object. ' ''' </summary> ' ''' <param name="sender">The source of the event.</param> ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> 'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved ' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then... ' Dim sb As New System.Text.StringBuilder ' sb.AppendLine("DRIVE DISCONNECTED!") ' sb.AppendLine() ' sb.AppendLine(String.Format("Drive Name: {0}", e.Name)) ' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType)) ' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat)) ' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady)) ' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory)) ' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel)) ' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize)) ' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace)) ' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace)) ' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information) ' End If 'End Sub #End Region #Region " Imports " Imports System.IO Imports System.Runtime.InteropServices Imports System.ComponentModel #End Region ''' <summary> ''' Device insertion/removal monitor. ''' </summary> Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable #Region " Objects " ''' <summary> ''' The current connected drives. ''' </summary> Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo ) ''' <summary> ''' Indicates the drive letter of the current device. ''' </summary> Private DriveLetter As Char = Nothing ''' <summary> ''' Indicates the current Drive information. ''' </summary> Private CurrentDrive As DriveWatcherInfo = Nothing ''' <summary> ''' The form to manage their Windows Messages. ''' </summary> Private WithEvents form As Form = Nothing #End Region #Region " Events " ''' <summary> ''' Occurs when a drive is inserted. ''' </summary> Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo) ''' <summary> ''' Occurs when a drive is removed. ''' </summary> Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo) #End Region #Region " Enumerations " ''' <summary> ''' Notifies an application of a change to the hardware configuration of a device or the computer. ''' A window receives this message through its WindowProc function. ''' For more info, see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx ''' </summary> Private Enum DeviceEvents As Integer ''' <summary> ''' The current configuration has changed, due to a dock or undock. ''' </summary> Change = &H219 ''' <summary> ''' A device or piece of media has been inserted and becomes available. ''' </summary> Arrival = &H8000 ''' <summary> ''' Request permission to remove a device or piece of media. ''' This message is the last chance for applications and drivers to prepare for this removal. ''' However, any application can deny this request and cancel the operation. ''' </summary> QueryRemove = &H8001 ''' <summary> ''' A request to remove a device or piece of media has been canceled. ''' </summary> QueryRemoveFailed = &H8002 ''' <summary> ''' A device or piece of media is being removed and is no longer available for use. ''' </summary> RemovePending = &H8003 ''' <summary> ''' A device or piece of media has been removed. ''' </summary> RemoveComplete = &H8004 ''' <summary> ''' The type volume ''' </summary> TypeVolume = &H2 End Enum #End Region #Region " Structures " ''' <summary> ''' Indicates information related of a Device. ''' ( Replic of System.IO.DriveInfo ) ''' </summary> Public Structure DriveWatcherInfo ''' <summary> ''' Indicates the name of a drive, such as 'C:\'. ''' </summary> Public Name As String ''' <summary> ''' Indicates the amount of available free space on a drive, in bytes. ''' </summary> Public AvailableFreeSpace As Long ''' <summary> ''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc... ''' </summary> Public DriveFormat As String ''' <summary> ''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc... ''' </summary> Public DriveType As DriveType ''' <summary> ''' Indicates whether a drive is ready. ''' </summary> Public IsReady As Boolean ''' <summary> ''' Indicates the root directory of a drive. ''' </summary> Public RootDirectory As String ''' <summary> ''' Indicates the total amount of free space available on a drive, in bytes. ''' </summary> Public TotalFreeSpace As Long ''' <summary> ''' Indicates the total size of storage space on a drive, in bytes. ''' </summary> Public TotalSize As Long ''' <summary> ''' Indicates the volume label of a drive. ''' </summary> Public VolumeLabel As String ''' <summary> ''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct. ''' </summary> ''' <param name="e">The e.</param> Public Sub New(ByVal e As DriveInfo) Name = e.Name Select Case e.IsReady Case True ' Drive is formatted and ready. IsReady = True DriveFormat = e.DriveFormat DriveType = e.DriveType RootDirectory = e.RootDirectory.FullName VolumeLabel = e.VolumeLabel TotalSize = e.TotalSize TotalFreeSpace = e.TotalFreeSpace AvailableFreeSpace = e.AvailableFreeSpace Case False ' Drive is not formatted so can't retrieve data. IsReady = False DriveFormat = Nothing DriveType = e.DriveType RootDirectory = e.RootDirectory.FullName VolumeLabel = Nothing TotalSize = 0 TotalFreeSpace = 0 AvailableFreeSpace = 0 End Select ' e.IsReady End Sub End Structure ''' <summary> ''' Contains information about a logical volume. ''' For more info, see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx ''' </summary> <StructLayout(LayoutKind.Sequential)> Private Structure DEV_BROADCAST_VOLUME ''' <summary> ''' The size of this structure, in bytes. ''' </summary> Public Size As UInteger ''' <summary> ''' Set to DBT_DEVTYP_VOLUME (2). ''' </summary> Public Type As UInteger ''' <summary> ''' Reserved parameter; do not use this. ''' </summary> Public Reserved As UInteger ''' <summary> ''' The logical unit mask identifying one or more logical units. ''' Each bit in the mask corresponds to one logical drive. ''' Bit 0 represents drive A, bit 1 represents drive B, and so on. ''' </summary> Public Mask As UInteger ''' <summary> ''' This parameter can be one of the following values: ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive. ''' '0x0002': Indicated logical volume is a network volume. ''' </summary> Public Flags As UShort End Structure #End Region #Region " Constructor " ''' <summary> ''' Initializes a new instance of this class. ''' </summary> ''' <param name="form">The form to assign.</param> Public Sub New(ByVal form As Form) ' Assign the Formulary. Me.form = form End Sub #End Region #Region " Event Handlers " ''' <summary> ''' Assign the handle of the target Form to this NativeWindow, ''' necessary to override target Form's WndProc. ''' </summary> Private Sub SetFormHandle() _ Handles form.HandleCreated, form.Load, form.Shown If Not MyBase.Handle.Equals(Me.form.Handle) Then MyBase.AssignHandle(Me.form.Handle) End If End Sub ''' <summary> ''' Releases the Handle. ''' </summary> Private Sub OnHandleDestroyed() _ Handles form.HandleDestroyed MyBase.ReleaseHandle() End Sub #End Region #Region " Private Methods " ''' <summary> ''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object. ''' </summary> ''' <param name="Device"> ''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask. ''' </param> ''' <returns>System.Char.</returns> Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char Dim DriveLetters As Char() = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" } Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask)) For X As Integer = 0 To DeviceID.Length If DeviceID(X) Then Return DriveLetters(X) End If Next X Return Nothing End Function #End Region #Region " WndProc" ''' <summary> ''' Invokes the default window procedure associated with this window to process messages for this Window. ''' </summary> ''' <param name="m"> ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message. ''' </param> Protected Overrides Sub WndProc(ByRef m As Message) Select Case m.Msg Case DeviceEvents.Change ' The hardware has changed. ' Transform the LParam pointer into the data structure. Dim CurrentWDrive As DEV_BROADCAST_VOLUME = CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME) Select Case m.WParam.ToInt32 Case DeviceEvents.Arrival ' The device is connected. ' Get the drive letter of the connected device. DriveLetter = GetDriveLetter(CurrentWDrive) ' Get the drive information of the connected device. CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter)) ' If it's an storage device then... If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then ' Inform that the device is connected by raising the 'DriveConnected' event. RaiseEvent DriveInserted(Me, CurrentDrive) ' Add the connected device to the dictionary, to retrieve info. If Not CurrentDrives.ContainsKey(DriveLetter) Then CurrentDrives.Add(DriveLetter, CurrentDrive) End If ' Not CurrentDrives.ContainsKey(DriveLetter) End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Case DeviceEvents.QueryRemove ' The device is preparing to be removed. ' Get the letter of the current device being removed. DriveLetter = GetDriveLetter(CurrentWDrive) ' If the current device being removed is not in the dictionary then... If Not CurrentDrives.ContainsKey(DriveLetter) Then ' Get the device information of the current device being removed. CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter)) ' Add the current device to the dictionary, ' to retrieve info before lost it after fully-removal. CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter))) End If ' Not CurrentDrives.ContainsKey(DriveLetter) Case DeviceEvents.RemoveComplete ' Get the letter of the removed device. DriveLetter = GetDriveLetter(CurrentWDrive) ' Inform that the device is disconnected by raising the 'DriveDisconnected' event. RaiseEvent DriveRemoved(Me, CurrentDrive) ' If the removed device is in the dictionary then... If CurrentDrives.ContainsKey(DriveLetter) Then ' Remove the device from the dictionary. CurrentDrives.Remove(DriveLetter) End If ' CurrentDrives.ContainsKey(DriveLetter) End Select ' m.WParam.ToInt32 End Select ' m.Msg MyBase.WndProc(m) ' Return Message to base message handler. End Sub #End Region #Region " Hidden methods " ' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods. ' NOTE: The methods can be re-enabled at any-time if needed. ''' <summary> ''' Assigns a handle to this window. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub AssignHandle() End Sub ''' <summary> ''' Creates a window and its handle with the specified creation parameters. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub CreateHandle() End Sub ''' <summary> ''' Creates an object that contains all the relevant information required ''' to generate a proxy used to communicate with a remote object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub CreateObjRef() End Sub ''' <summary> ''' Invokes the default window procedure associated with this window. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub DefWndProc() End Sub ''' <summary> ''' Destroys the window and its handle. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub DestroyHandle() End Sub ''' <summary> ''' Determines whether the specified object is equal to the current object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub Equals() End Sub ''' <summary> ''' Serves as the default hash function. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub GetHashCode() End Sub ''' <summary> ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub GetLifetimeService() End Sub ''' <summary> ''' Obtains a lifetime service object to control the lifetime policy for this instance. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub InitializeLifetimeService() End Sub ''' <summary> ''' Releases the handle associated with this window. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub ReleaseHandle() End Sub ''' <summary> ''' Gets the handle for this window. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Property Handle() #End Region #Region " IDisposable " ''' <summary> ''' To detect redundant calls when disposing. ''' </summary> Private IsDisposed As Boolean = False ''' <summary> ''' Prevent calls to methods after disposing. ''' </summary> ''' <exception cref="System.ObjectDisposedException"></exception> Private Sub DisposedCheck() If Me.IsDisposed Then Throw New ObjectDisposedException(Me.GetType().FullName) End If End Sub ''' <summary> ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub ''' <summary> ''' Releases unmanaged and - optionally - managed resources. ''' </summary> ''' <param name="IsDisposing"> ''' <c>true</c> to release both managed and unmanaged resources; ''' <c>false</c> to release only unmanaged resources. ''' </param> Protected Sub Dispose(ByVal IsDisposing As Boolean) If Not Me.IsDisposed Then If IsDisposing Then Me.form = Nothing MyBase.ReleaseHandle() MyBase.DestroyHandle() End If End If Me.IsDisposed = True End Sub #End Region 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  ) ¿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. ' *********************************************************************** ' Author : Elektro ' Modified : 02-17-2014 ' *********************************************************************** ' <copyright file="DriveWatcher.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " ' ''' <summary> ' ''' The DriveWatcher instance to monitor USB devices. ' ''' </summary> 'Friend WithEvents USBMonitor As New DriveWatcher(form:=Me) ' ''' <summary> ' ''' Handles the DriveInserted event of the USBMonitor object. ' ''' </summary> ' ''' <param name="sender">The source of the event.</param> ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> 'Private Sub USBMonitor_DriveInserted(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveInserted ' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then... ' Dim sb As New System.Text.StringBuilder ' sb.AppendLine("DRIVE CONNECTED!") ' sb.AppendLine() ' sb.AppendLine(String.Format("Drive Name: {0}", e.Name)) ' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType)) ' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat)) ' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady)) ' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory)) ' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel)) ' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize)) ' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace)) ' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace)) ' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information) ' End If 'End Sub ' ''' <summary> ' ''' Handles the DriveRemoved event of the USBMonitor object. ' ''' </summary> ' ''' <param name="sender">The source of the event.</param> ' ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> 'Private Sub USBMonitor_DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcher.DriveWatcherInfo) Handles USBMonitor.DriveRemoved ' If e.DriveType = IO.DriveType.Removable Then ' If it's a removable media then... ' Dim sb As New System.Text.StringBuilder ' sb.AppendLine("DRIVE DISCONNECTED!") ' sb.AppendLine() ' sb.AppendLine(String.Format("Drive Name: {0}", e.Name)) ' sb.AppendLine(String.Format("Drive Type: {0}", e.DriveType)) ' sb.AppendLine(String.Format("FileSystem: {0}", e.DriveFormat)) ' sb.AppendLine(String.Format("Is Ready? : {0}", e.IsReady)) ' sb.AppendLine(String.Format("Root Dir. : {0}", e.RootDirectory)) ' sb.AppendLine(String.Format("Vol. Label: {0}", e.VolumeLabel)) ' sb.AppendLine(String.Format("Total Size: {0}", e.TotalSize)) ' sb.AppendLine(String.Format("Free Space: {0}", e.TotalFreeSpace)) ' sb.AppendLine(String.Format("Ava. Space: {0}", e.AvailableFreeSpace)) ' MessageBox.Show(sb.ToString, "USBMonitor", MessageBoxButtons.OK, MessageBoxIcon.Information) ' End If 'End Sub #End Region #Region " Imports " Imports System.IO Imports System.Runtime.InteropServices Imports System.ComponentModel #End Region ''' <summary> ''' Device insertion/removal monitor. ''' </summary> Public Class DriveWatcher : Inherits NativeWindow : Implements IDisposable #Region " Objects " ''' <summary> ''' The current connected drives. ''' </summary> Private CurrentDrives As New Dictionary(Of Char, DriveWatcherInfo ) ''' <summary> ''' Indicates the drive letter of the current device. ''' </summary> Private DriveLetter As Char = Nothing ''' <summary> ''' Indicates the current Drive information. ''' </summary> Private CurrentDrive As DriveWatcherInfo = Nothing ''' <summary> ''' The form to manage their Windows Messages. ''' </summary> Private WithEvents form As Form = Nothing #End Region #Region " Events " ''' <summary> ''' Occurs when a drive is inserted. ''' </summary> Public Event DriveInserted(ByVal sender As Object, ByVal e As DriveWatcherInfo) ''' <summary> ''' Occurs when a drive is removed. ''' </summary> Public Event DriveRemoved(ByVal sender As Object, ByVal e As DriveWatcherInfo) #End Region #Region " Enumerations " ''' <summary> ''' Notifies an application of a change to the hardware configuration of a device or the computer. ''' A window receives this message through its WindowProc function. ''' For more info, see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480%28v=vs.85%29.aspx ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363232%28v=vs.85%29.aspx ''' </summary> Private Enum DeviceEvents As Integer ''' <summary> ''' The current configuration has changed, due to a dock or undock. ''' </summary> Change = &H219 ''' <summary> ''' A device or piece of media has been inserted and becomes available. ''' </summary> Arrival = &H8000 ''' <summary> ''' Request permission to remove a device or piece of media. ''' This message is the last chance for applications and drivers to prepare for this removal. ''' However, any application can deny this request and cancel the operation. ''' </summary> QueryRemove = &H8001 ''' <summary> ''' A request to remove a device or piece of media has been canceled. ''' </summary> QueryRemoveFailed = &H8002 ''' <summary> ''' A device or piece of media is being removed and is no longer available for use. ''' </summary> RemovePending = &H8003 ''' <summary> ''' A device or piece of media has been removed. ''' </summary> RemoveComplete = &H8004 ''' <summary> ''' The type volume ''' </summary> TypeVolume = &H2 End Enum #End Region #Region " Structures " ''' <summary> ''' Indicates information related of a Device. ''' ( Replic of System.IO.DriveInfo ) ''' </summary> Public Structure DriveWatcherInfo ''' <summary> ''' Indicates the name of a drive, such as 'C:\'. ''' </summary> Public Name As String ''' <summary> ''' Indicates the amount of available free space on a drive, in bytes. ''' </summary> Public AvailableFreeSpace As Long ''' <summary> ''' Indicates the name of the filesystem, such as 'NTFS', 'FAT32', 'UDF', etc... ''' </summary> Public DriveFormat As String ''' <summary> ''' Indicates the the drive type, such as 'CD-ROM', 'removable', 'fixed', etc... ''' </summary> Public DriveType As DriveType ''' <summary> ''' Indicates whether a drive is ready. ''' </summary> Public IsReady As Boolean ''' <summary> ''' Indicates the root directory of a drive. ''' </summary> Public RootDirectory As String ''' <summary> ''' Indicates the total amount of free space available on a drive, in bytes. ''' </summary> Public TotalFreeSpace As Long ''' <summary> ''' Indicates the total size of storage space on a drive, in bytes. ''' </summary> Public TotalSize As Long ''' <summary> ''' Indicates the volume label of a drive. ''' </summary> Public VolumeLabel As String ''' <summary> ''' Initializes a new instance of the <see cref="DriveWatcherInfo"/> struct. ''' </summary> ''' <param name="e">The e.</param> Public Sub New(ByVal e As DriveInfo) Name = e.Name Select Case e.IsReady Case True ' Drive is formatted and ready. IsReady = True DriveFormat = e.DriveFormat DriveType = e.DriveType RootDirectory = e.RootDirectory.FullName VolumeLabel = e.VolumeLabel TotalSize = e.TotalSize TotalFreeSpace = e.TotalFreeSpace AvailableFreeSpace = e.AvailableFreeSpace Case False ' Drive is not formatted so can't retrieve data. IsReady = False DriveFormat = Nothing DriveType = e.DriveType RootDirectory = e.RootDirectory.FullName VolumeLabel = Nothing TotalSize = 0 TotalFreeSpace = 0 AvailableFreeSpace = 0 End Select ' e.IsReady End Sub End Structure ''' <summary> ''' Contains information about a logical volume. ''' For more info, see here: ''' http://msdn.microsoft.com/en-us/library/windows/desktop/aa363249%28v=vs.85%29.aspx ''' </summary> <StructLayout(LayoutKind.Sequential)> Private Structure DEV_BROADCAST_VOLUME ''' <summary> ''' The size of this structure, in bytes. ''' </summary> Public Size As UInteger ''' <summary> ''' Set to DBT_DEVTYP_VOLUME (2). ''' </summary> Public Type As UInteger ''' <summary> ''' Reserved parameter; do not use this. ''' </summary> Public Reserved As UInteger ''' <summary> ''' The logical unit mask identifying one or more logical units. ''' Each bit in the mask corresponds to one logical drive. ''' Bit 0 represents drive A, bit 1 represents drive B, and so on. ''' </summary> Public Mask As UInteger ''' <summary> ''' This parameter can be one of the following values: ''' '0x0001': Change affects media in drive. If not set, change affects physical device or drive. ''' '0x0002': Indicated logical volume is a network volume. ''' </summary> Public Flags As UShort End Structure #End Region #Region " Constructor " ''' <summary> ''' Initializes a new instance of this class. ''' </summary> ''' <param name="form">The form to assign.</param> Public Sub New(ByVal form As Form) ' Assign the Formulary. Me.form = form End Sub #End Region #Region " Event Handlers " ''' <summary> ''' Assign the handle of the target Form to this NativeWindow, ''' necessary to override target Form's WndProc. ''' </summary> Private Sub SetFormHandle() _ Handles form.HandleCreated, form.Load, form.Shown If Not MyBase.Handle.Equals(Me.form.Handle) Then MyBase.AssignHandle(Me.form.Handle) End If End Sub ''' <summary> ''' Releases the Handle. ''' </summary> Private Sub OnHandleDestroyed() _ Handles form.HandleDestroyed MyBase.ReleaseHandle() End Sub #End Region #Region " Private Methods " ''' <summary> ''' Gets the drive letter stored in a 'DEV_BROADCAST_VOLUME' structure object. ''' </summary> ''' <param name="Device"> ''' Indicates the 'DEV_BROADCAST_VOLUME' object containing the Device mask. ''' </param> ''' <returns>System.Char.</returns> Private Function GetDriveLetter(ByVal Device As DEV_BROADCAST_VOLUME) As Char Dim DriveLetters As Char() = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" } Dim DeviceID As New BitArray(BitConverter.GetBytes(Device.Mask)) For X As Integer = 0 To DeviceID.Length If DeviceID(X) Then Return DriveLetters(X) End If Next X Return Nothing End Function #End Region #Region " WndProc" ''' <summary> ''' Invokes the default window procedure associated with this window to process messages for this Window. ''' </summary> ''' <param name="m"> ''' A <see cref="T:System.Windows.Forms.Message" /> that is associated with the current Windows message. ''' </param> Protected Overrides Sub WndProc(ByRef m As Message) Select Case m.Msg Case DeviceEvents.Change ' The hardware has changed. ' Transform the LParam pointer into the data structure. Dim CurrentWDrive As DEV_BROADCAST_VOLUME = CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)), DEV_BROADCAST_VOLUME) Select Case m.WParam.ToInt32 Case DeviceEvents.Arrival ' The device is connected. ' Get the drive letter of the connected device. DriveLetter = GetDriveLetter(CurrentWDrive) ' Get the drive information of the connected device. CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter)) ' If it's an storage device then... If Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Then ' Inform that the device is connected by raising the 'DriveConnected' event. RaiseEvent DriveInserted(Me, CurrentDrive) ' Add the connected device to the dictionary, to retrieve info. If Not CurrentDrives.ContainsKey(DriveLetter) Then CurrentDrives.Add(DriveLetter, CurrentDrive) End If ' Not CurrentDrives.ContainsKey(DriveLetter) End If ' Marshal.ReadInt32(m.LParam, 4) = DeviceEvents.TypeVolume Case DeviceEvents.QueryRemove ' The device is preparing to be removed. ' Get the letter of the current device being removed. DriveLetter = GetDriveLetter(CurrentWDrive) ' If the current device being removed is not in the dictionary then... If Not CurrentDrives.ContainsKey(DriveLetter) Then ' Get the device information of the current device being removed. CurrentDrive = New DriveWatcherInfo(New DriveInfo(DriveLetter)) ' Add the current device to the dictionary, ' to retrieve info before lost it after fully-removal. CurrentDrives.Add(DriveLetter, New DriveWatcherInfo(New DriveInfo(DriveLetter))) End If ' Not CurrentDrives.ContainsKey(DriveLetter) Case DeviceEvents.RemoveComplete ' Get the letter of the removed device. DriveLetter = GetDriveLetter(CurrentWDrive) ' Inform that the device is disconnected by raising the 'DriveDisconnected' event. RaiseEvent DriveRemoved(Me, CurrentDrive) ' If the removed device is in the dictionary then... If CurrentDrives.ContainsKey(DriveLetter) Then ' Remove the device from the dictionary. CurrentDrives.Remove(DriveLetter) End If ' CurrentDrives.ContainsKey(DriveLetter) End Select ' m.WParam.ToInt32 End Select ' m.Msg MyBase.WndProc(m) ' Return Message to base message handler. End Sub #End Region #Region " Hidden methods " ' These methods and properties are purposely hidden from Intellisense just to look better without unneeded methods. ' NOTE: The methods can be re-enabled at any-time if needed. ''' <summary> ''' Assigns a handle to this window. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub AssignHandle() End Sub ''' <summary> ''' Creates a window and its handle with the specified creation parameters. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub CreateHandle() End Sub ''' <summary> ''' Creates an object that contains all the relevant information required ''' to generate a proxy used to communicate with a remote object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub CreateObjRef() End Sub ''' <summary> ''' Invokes the default window procedure associated with this window. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub DefWndProc() End Sub ''' <summary> ''' Destroys the window and its handle. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub DestroyHandle() End Sub ''' <summary> ''' Determines whether the specified object is equal to the current object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub Equals() End Sub ''' <summary> ''' Serves as the default hash function. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub GetHashCode() End Sub ''' <summary> ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub GetLifetimeService() End Sub ''' <summary> ''' Obtains a lifetime service object to control the lifetime policy for this instance. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub InitializeLifetimeService() End Sub ''' <summary> ''' Releases the handle associated with this window. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub ReleaseHandle() End Sub ''' <summary> ''' Gets the handle for this window. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Property Handle() #End Region #Region " IDisposable " ''' <summary> ''' To detect redundant calls when disposing. ''' </summary> Private IsDisposed As Boolean = False ''' <summary> ''' Prevent calls to methods after disposing. ''' </summary> ''' <exception cref="System.ObjectDisposedException"></exception> Private Sub DisposedCheck() If Me.IsDisposed Then Throw New ObjectDisposedException(Me.GetType().FullName) End If End Sub ''' <summary> ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub ''' <summary> ''' Releases unmanaged and - optionally - managed resources. ''' </summary> ''' <param name="IsDisposing"> ''' <c>true</c> to release both managed and unmanaged resources; ''' <c>false</c> to release only unmanaged resources. ''' </param> Protected Sub Dispose(ByVal IsDisposing As Boolean) If Not Me.IsDisposed Then If IsDisposing Then Me.form = Nothing MyBase.ReleaseHandle() MyBase.DestroyHandle() End If End If Me.IsDisposed = True End Sub #End Region End Class
Saludos.
|
|
|
|
|
|
|