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

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


  Mostrar Mensajes
Páginas: 1 ... 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 [681] 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 ... 1236
6801  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 21 Agosto 2014, 13:58 pm
Unos métodos de uso genérico para utilizar la librería IconLib ( http://www.codeproject.com/Articles/16178/IconLib-Icons-Unfolded-MultiIcon-and-Windows-Vista ) para crear iconos o leer las capas de un icono.

PD: Hay que modificar un poco el source (escrito en C#) para permitir la creación de iconos de 512 x 512 (es facil, busquen un if con "256" y añadan el valor "512" a la enumeración de formatos de iconos), pero por otro lado no hay ningún problema para leer este tamaño de icono sin realizar modificaciones.



Código
  1.    ' Create Icon
  2.    ' By Elektro
  3.    '
  4.    ' Usage Examples:
  5.    '
  6.    ' Dim IconFile As IconLib.SingleIcon = CreateIcon("C:\Image.ico", IconLib.IconOutputFormat.All)
  7.    ' For Each IconLayer As IconLib.IconImage In IconFile
  8.    '     PictureBox1.BackgroundImage = IconLayer.Icon.ToBitmap
  9.    '     Debug.WriteLine(IconLayer.Icon.Size.ToString)
  10.    '     Application.DoEvents()
  11.    '     Threading.Thread.Sleep(750)
  12.    ' Next IconLayer
  13.    '
  14.    ''' <summary>
  15.    ''' Creates an icon with the specified image.
  16.    ''' </summary>
  17.    ''' <param name="imagefile">Indicates the image.</param>
  18.    ''' <param name="format">Indicates the icon format.</param>
  19.    ''' <returns>IconLib.SingleIcon.</returns>
  20.    Public Function CreateIcon(ByVal imagefile As String,
  21.                               Optional ByVal format As IconLib.IconOutputFormat =
  22.                                                        IconLib.IconOutputFormat.All) As IconLib.SingleIcon
  23.  
  24.        Dim sIcon As IconLib.SingleIcon = New IconLib.MultiIcon().Add("Icon1")
  25.        sIcon.CreateFrom(imagefile, format)
  26.  
  27.        Return sIcon
  28.  
  29.    End Function
  30.  
  31.    ' Get Icon-Layers
  32.    ' By Elektro
  33.    '
  34.    ' Usage Examples:
  35.    '
  36.    ' For Each IconLayer As IconLib.IconImage In GetIconLayers("C:\Image.ico")
  37.    '     PictureBox1.BackgroundImage = IconLayer.Icon.ToBitmap
  38.    '     Debug.WriteLine(IconLayer.Icon.Size.ToString)
  39.    '     Application.DoEvents()
  40.    '     Threading.Thread.Sleep(750)
  41.    ' Next IconLayer
  42.    '
  43.    ''' <summary>
  44.    ''' Gets all the icon layers inside an icon file.
  45.    ''' </summary>
  46.    ''' <param name="iconfile">Indicates the icon file.</param>
  47.    ''' <returns>IconLib.SingleIcon.</returns>
  48.    Public Function GetIconLayers(ByVal iconfile As String) As IconLib.SingleIcon
  49.  
  50.        Dim mIcon As IconLib.MultiIcon = New IconLib.MultiIcon()
  51.        mIcon.Load(iconfile)
  52.  
  53.        Return mIcon.First
  54.  
  55.    End Function
  56.  
6802  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 21 Agosto 2014, 13:03 pm
Una class para ordenar los items de un listview según la columna:



Código
  1. ' ***********************************************************************
  2. ' Author           : Elektro
  3. ' Last Modified On : 08-20-2014
  4. ' ***********************************************************************
  5. ' <copyright file="ListView Column-Sorter.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Public Class ListViewColumnSorter_TestForm : Inherits form
  13. '
  14. '    ''' <summary>
  15. '    ''' The listview to sort.
  16. '    ''' </summary>
  17. '    Private WithEvents LV As New ListView
  18. '
  19. '    ''' <summary>
  20. '    ''' The 'ListViewColumnSorter' instance.
  21. '    ''' </summary>
  22. '    Private Sorter As New ListViewColumnSorter
  23. '
  24. '    ''' <summary>
  25. '    ''' Initializes a new instance of the <see cref="ListViewColumnSorter_TestForm"/> class.
  26. '    ''' </summary>
  27. '    Public Sub New()
  28. '
  29. '        ' This call is required by the designer.
  30. '        InitializeComponent()
  31. '
  32. '        With LV ' Set the Listview properties.
  33. '
  34. '            ' Set the sorter, our 'ListViewColumnSorter'.
  35. '            .ListViewItemSorter = Sorter
  36. '
  37. '            ' The sorting default direction.
  38. '            .Sorting = SortOrder.Ascending
  39. '
  40. '            ' Set the default sort-modifier.
  41. '            Sorter.SortModifier = ListViewColumnSorter.SortModifiers.SortByText
  42. '
  43. '            ' Add some columns.
  44. '            .Columns.Add("Text").Tag = ListViewColumnSorter.SortModifiers.SortByText
  45. '            .Columns.Add("Numbers").Tag = ListViewColumnSorter.SortModifiers.SortByNumber
  46. '            .Columns.Add("Dates").Tag = ListViewColumnSorter.SortModifiers.SortByDate
  47. '
  48. '            ' Adjust the column sizes.
  49. '            For Each col As ColumnHeader In LV.Columns
  50. '                col.Width = 100I
  51. '            Next
  52. '
  53. '            ' Add some items.
  54. '            .Items.Add("hello").SubItems.AddRange({"1", "11/11/2000"})
  55. '            .Items.Add("yeehaa!").SubItems.AddRange({"2", "11-11-2000"})
  56. '            .Items.Add("El3ktr0").SubItems.AddRange({"10", "9/9/1999"})
  57. '            .Items.Add("wow").SubItems.AddRange({"100", "21/08/2014"})
  58. '
  59. '            ' Visual-Style things.
  60. '            .Dock = DockStyle.Fill
  61. '            .View = View.Details
  62. '            .FullRowSelect = True
  63. '
  64. '        End With
  65. '
  66. '        With Me ' Set the Form properties.
  67. '
  68. '            .Size = New Size(400, 200)
  69. '            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
  70. '            .MaximizeBox = False
  71. '            .StartPosition = FormStartPosition.CenterScreen
  72. '            .Text = "ListViewColumnSorter TestForm"
  73. '
  74. '        End With
  75. '
  76. '        ' Add the Listview to UI.
  77. '        Me.Controls.Add(LV)
  78. '
  79. '    End Sub
  80. '
  81. '    ''' <summary>
  82. '    ''' Handles the 'ColumnClick' event of the 'ListView1' control.
  83. '    ''' </summary>
  84. '    Private Sub ListView1_ColumnClick(ByVal sender As Object, ByVal e As ColumnClickEventArgs) _
  85. '    Handles LV.ColumnClick
  86. '
  87. '        ' Dinamycaly sets the sort-modifier to sort the column by text, number, or date.
  88. '        Sorter.SortModifier = sender.columns(e.Column).tag
  89. '
  90. '        ' Determine whether clicked column is already the column that is being sorted.
  91. '        If e.Column = Sorter.Column Then
  92. '
  93. '            ' Reverse the current sort direction for this column.
  94. '            If Sorter.Order = SortOrder.Ascending Then
  95. '                Sorter.Order = SortOrder.Descending
  96. '
  97. '            Else
  98. '                Sorter.Order = SortOrder.Ascending
  99. '
  100. '            End If ' Sorter.Order
  101. '
  102. '        Else
  103. '
  104. '            ' Set the column number that is to be sorted, default to ascending.
  105. '            Sorter.Column = e.Column
  106. '            Sorter.Order = SortOrder.Ascending
  107. '
  108. '        End If ' e.Column
  109. '
  110. '        ' Perform the sort with these new sort options.
  111. '        sender.Sort()
  112. '
  113. '    End Sub
  114. '
  115. 'End Class
  116.  
  117. #End Region
  118.  
  119. #Region " Imports "
  120.  
  121. Imports System.Text.RegularExpressions
  122. Imports System.ComponentModel
  123.  
  124. #End Region
  125.  
  126. #Region " ListView Column-Sorter "
  127.  
  128. ''' <summary>
  129. ''' Performs a sorting comparison.
  130. ''' </summary>
  131. Public Class ListViewColumnSorter : Implements IComparer
  132.  
  133. #Region " Objects "
  134.  
  135.    '''' <summary>
  136.    '''' Indicates the comparer instance.
  137.    '''' </summary>
  138.    Private Comparer As Object = New TextComparer
  139.  
  140. #End Region
  141.  
  142. #Region " Properties "
  143.  
  144.    ''' <summary>
  145.    ''' Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
  146.    ''' </summary>
  147.    Public Property Column As Integer
  148.        Get
  149.            Return Me._Column
  150.        End Get
  151.        Set(ByVal value As Integer)
  152.            Me._Column = value
  153.        End Set
  154.    End Property
  155.    Private _Column As Integer = 0I
  156.  
  157.    ''' <summary>
  158.    ''' Gets or sets the order of sorting to apply.
  159.    ''' </summary>
  160.    Public Property Order As SortOrder
  161.        Get
  162.            Return Me._Order
  163.        End Get
  164.        Set(ByVal value As SortOrder)
  165.            Me._Order = value
  166.        End Set
  167.    End Property
  168.    Private _Order As SortOrder = SortOrder.None
  169.  
  170.    ''' <summary>
  171.    ''' Gets or sets the sort modifier.
  172.    ''' </summary>
  173.    ''' <value>The sort modifier.</value>
  174.    Public Property SortModifier As SortModifiers
  175.        Get
  176.            Return Me._SortModifier
  177.        End Get
  178.        Set(ByVal value As SortModifiers)
  179.            Me._SortModifier = value
  180.        End Set
  181.    End Property
  182.    Private _SortModifier As SortModifiers = SortModifiers.SortByText
  183.  
  184. #End Region
  185.  
  186. #Region " Enumerations "
  187.  
  188.    ''' <summary>
  189.    ''' Specifies a comparison result.
  190.    ''' </summary>
  191.    Public Enum ComparerResult As Integer
  192.  
  193.        ''' <summary>
  194.        ''' 'X' is equals to 'Y'.
  195.        ''' </summary>
  196.        Equals = 0I
  197.  
  198.        ''' <summary>
  199.        ''' 'X' is less than 'Y'.
  200.        ''' </summary>
  201.        Less = -1I
  202.  
  203.        ''' <summary>
  204.        ''' 'X' is greater than 'Y'.
  205.        ''' </summary>
  206.        Greater = 1I
  207.  
  208.    End Enum
  209.  
  210.    ''' <summary>
  211.    ''' Indicates a Sorting Modifier.
  212.    ''' </summary>
  213.    Public Enum SortModifiers As Integer
  214.  
  215.        ''' <summary>
  216.        ''' Treats the values &#8203;&#8203;as text.
  217.        ''' </summary>
  218.        SortByText = 0I
  219.  
  220.        ''' <summary>
  221.        ''' Treats the values &#8203;&#8203;as numbers.
  222.        ''' </summary>
  223.        SortByNumber = 1I
  224.  
  225.        ''' <summary>
  226.        ''' Treats valuesthe values &#8203;&#8203;as dates.
  227.        ''' </summary>
  228.        SortByDate = 2I
  229.  
  230.    End Enum
  231.  
  232. #End Region
  233.  
  234. #Region " Private Methods "
  235.  
  236.    ''' <summary>
  237.    ''' Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
  238.    ''' </summary>
  239.    ''' <param name="x">The first object to compare.</param>
  240.    ''' <param name="y">The second object to compare.</param>
  241.    ''' <returns>
  242.    ''' A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>,
  243.    ''' 0: <paramref name="x"/> equals <paramref name="y"/>.
  244.    ''' Less than 0: <paramref name="x"/> is less than <paramref name="y"/>.
  245.    ''' Greater than 0: <paramref name="x"/> is greater than <paramref name="y"/>.
  246.    ''' </returns>
  247.    Private Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
  248.  
  249.        Dim CompareResult As ComparerResult = ComparerResult.Equals
  250.        Dim LVItemX, LVItemY As ListViewItem
  251.  
  252.        ' Cast the objects to be compared
  253.        LVItemX = DirectCast(x, ListViewItem)
  254.        LVItemY = DirectCast(y, ListViewItem)
  255.  
  256.        Dim strX As String = If(Not LVItemX.SubItems.Count <= Me._Column,
  257.                               LVItemX.SubItems(Me._Column).Text,
  258.                               Nothing)
  259.  
  260.        Dim strY As String = If(Not LVItemY.SubItems.Count <= Me._Column,
  261.                                LVItemY.SubItems(Me._Column).Text,
  262.                                Nothing)
  263.  
  264.        Dim listViewMain As ListView = LVItemX.ListView
  265.  
  266.        ' Calculate correct return value based on object comparison
  267.        If listViewMain.Sorting <> SortOrder.Ascending AndAlso listViewMain.Sorting <> SortOrder.Descending Then
  268.  
  269.            ' Return '0' to indicate they are equal
  270.            Return ComparerResult.Equals
  271.  
  272.        End If
  273.  
  274.        If Me._SortModifier.Equals(SortModifiers.SortByText) Then
  275.  
  276.            ' Compare the two items
  277.            If LVItemX.SubItems.Count <= Me._Column AndAlso LVItemY.SubItems.Count <= Me._Column Then
  278.                CompareResult = Me.Comparer.Compare(Nothing, Nothing)
  279.  
  280.            ElseIf LVItemX.SubItems.Count <= Me._Column AndAlso LVItemY.SubItems.Count > Me._Column Then
  281.                CompareResult = Me.Comparer.Compare(Nothing, strY)
  282.  
  283.            ElseIf LVItemX.SubItems.Count > Me._Column AndAlso LVItemY.SubItems.Count <= Me._Column Then
  284.                CompareResult = Me.Comparer.Compare(strX, Nothing)
  285.  
  286.            Else
  287.                CompareResult = Me.Comparer.Compare(strX, strY)
  288.  
  289.            End If
  290.  
  291.        Else ' Me._SortModifier IsNot 'SortByText'
  292.  
  293.            Select Case Me._SortModifier
  294.  
  295.                Case SortModifiers.SortByNumber
  296.                    If Me.Comparer.GetType <> GetType(NumericComparer) Then
  297.                        Me.Comparer = New NumericComparer
  298.                    End If
  299.  
  300.                Case SortModifiers.SortByDate
  301.                    If Me.Comparer.GetType <> GetType(DateComparer) Then
  302.                        Me.Comparer = New DateComparer
  303.                    End If
  304.  
  305.                Case Else
  306.                    If Me.Comparer.GetType <> GetType(TextComparer) Then
  307.                        Me.Comparer = New TextComparer
  308.                    End If
  309.  
  310.            End Select
  311.  
  312.            CompareResult = Comparer.Compare(strX, strY)
  313.  
  314.        End If ' Me._SortModifier.Equals(...)
  315.  
  316.        ' Calculate correct return value based on object comparison
  317.        If Me._Order = SortOrder.Ascending Then
  318.            ' Ascending sort is selected, return normal result of compare operation
  319.            Return CompareResult
  320.  
  321.        ElseIf Me._Order = SortOrder.Descending Then
  322.            ' Descending sort is selected, return negative result of compare operation
  323.            Return (-CompareResult)
  324.  
  325.        Else
  326.            ' Return '0' to indicate they are equal
  327.            Return 0I
  328.  
  329.        End If ' Me._Order = ...
  330.  
  331.    End Function
  332.  
  333. #End Region
  334.  
  335. #Region " Hidden Methods "
  336.  
  337.    ''' <summary>
  338.    ''' Serves as a hash function for a particular type.
  339.    ''' </summary>
  340.    <EditorBrowsable(EditorBrowsableState.Never)>
  341.    Public Shadows Sub GetHashCode()
  342.    End Sub
  343.  
  344.    ''' <summary>
  345.    ''' Determines whether the specified System.Object instances are considered equal.
  346.    ''' </summary>
  347.    <EditorBrowsable(EditorBrowsableState.Never)>
  348.    Public Shadows Sub Equals()
  349.    End Sub
  350.  
  351.    ''' <summary>
  352.    ''' Gets the System.Type of the current instance.
  353.    ''' </summary>
  354.    ''' <returns>The exact runtime type of the current instance.</returns>
  355.    <EditorBrowsable(EditorBrowsableState.Never)>
  356.    Public Shadows Function [GetType]()
  357.        Return Me.GetType
  358.    End Function
  359.  
  360.    ''' <summary>
  361.    ''' Returns a String that represents the current object.
  362.    ''' </summary>
  363.    <EditorBrowsable(EditorBrowsableState.Never)>
  364.    Public Shadows Sub ToString()
  365.    End Sub
  366.  
  367. #End Region
  368.  
  369. End Class
  370.  
  371. #End Region
  372.  
  373. #Region " Comparers "
  374.  
  375. #Region " Text "
  376.  
  377. ''' <summary>
  378. ''' Performs a text comparison.
  379. ''' </summary>
  380. Public Class TextComparer : Inherits CaseInsensitiveComparer
  381.  
  382. #Region " Enumerations "
  383.  
  384.    ''' <summary>
  385.    ''' Specifies a comparison result.
  386.    ''' </summary>
  387.    Public Enum ComparerResult As Integer
  388.  
  389.        ''' <summary>
  390.        ''' 'X' is equals to 'Y'.
  391.        ''' </summary>
  392.        Equals = 0I
  393.  
  394.        ''' <summary>
  395.        ''' 'X' is less than 'Y'.
  396.        ''' </summary>
  397.        Less = -1I
  398.  
  399.        ''' <summary>
  400.        ''' 'X' is greater than 'Y'.
  401.        ''' </summary>
  402.        Greater = 1I
  403.  
  404.    End Enum
  405.  
  406. #End Region
  407.  
  408. #Region " Methods "
  409.  
  410.    ''' <summary>
  411.    ''' Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
  412.    ''' </summary>
  413.    ''' <param name="x">The first object to compare.</param>
  414.    ''' <param name="y">The second object to compare.</param>
  415.    ''' <returns>
  416.    ''' A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>,
  417.    ''' 0: <paramref name="x"/> equals <paramref name="y"/>.
  418.    ''' Less than 0: <paramref name="x"/> is less than <paramref name="y"/>.
  419.    ''' Greater than 0: <paramref name="x"/> is greater than <paramref name="y"/>.
  420.    ''' </returns>
  421.    Friend Shadows Function Compare(ByVal x As Object, ByVal y As Object) As Integer
  422.  
  423.        ' Null parsing.
  424.        If x Is Nothing AndAlso y Is Nothing Then
  425.            Return ComparerResult.Equals ' X is equals to Y.
  426.  
  427.        ElseIf x Is Nothing AndAlso y IsNot Nothing Then
  428.            Return ComparerResult.Less ' X is less than Y.
  429.  
  430.        ElseIf x IsNot Nothing AndAlso y Is Nothing Then
  431.            Return ComparerResult.Greater ' X is greater than Y.
  432.  
  433.        End If
  434.  
  435.        ' String parsing:
  436.        If (TypeOf x Is String) AndAlso (TypeOf y Is String) Then ' True and True
  437.            Return [Enum].Parse(GetType(ComparerResult),
  438.                                MyBase.Compare(x, y))
  439.  
  440.        ElseIf (TypeOf x Is String) AndAlso Not (TypeOf y Is String) Then ' True and False
  441.            Return ComparerResult.Greater ' X is greater than Y.
  442.  
  443.        ElseIf Not (TypeOf x Is String) AndAlso (TypeOf y Is String) Then ' False and True
  444.            Return ComparerResult.Less ' X is less than Y.
  445.  
  446.        Else ' False and False
  447.            Return ComparerResult.Equals
  448.  
  449.        End If
  450.  
  451.    End Function
  452.  
  453. #End Region
  454.  
  455. End Class
  456.  
  457. #End Region
  458.  
  459. #Region " Numeric "
  460.  
  461. ''' <summary>
  462. ''' Performs a numeric comparison.
  463. ''' </summary>
  464. Public Class NumericComparer : Implements IComparer
  465.  
  466. #Region " Enumerations "
  467.  
  468.    ''' <summary>
  469.    ''' Specifies a comparison result.
  470.    ''' </summary>
  471.    Public Enum ComparerResult As Integer
  472.  
  473.        ''' <summary>
  474.        ''' 'X' is equals to 'Y'.
  475.        ''' </summary>
  476.        Equals = 0I
  477.  
  478.        ''' <summary>
  479.        ''' 'X' is less than 'Y'.
  480.        ''' </summary>
  481.        Less = -1I
  482.  
  483.        ''' <summary>
  484.        ''' 'X' is greater than 'Y'.
  485.        ''' </summary>
  486.        Greater = 1I
  487.  
  488.    End Enum
  489.  
  490. #End Region
  491.  
  492. #Region " Methods "
  493.  
  494.    ''' <summary>
  495.    ''' Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
  496.    ''' </summary>
  497.    ''' <param name="x">The first object to compare.</param>
  498.    ''' <param name="y">The second object to compare.</param>
  499.    ''' <returns>
  500.    ''' A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>,
  501.    ''' 0: <paramref name="x"/> equals <paramref name="y"/>.
  502.    ''' Less than 0: <paramref name="x" /> is less than <paramref name="y"/>.
  503.    ''' Greater than 0: <paramref name="x"/> is greater than <paramref name="y"/>.
  504.    ''' </returns>
  505.    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
  506.    Implements IComparer.Compare
  507.  
  508.        ' Null parsing.
  509.        If x Is Nothing AndAlso y Is Nothing Then
  510.            Return ComparerResult.Equals ' X is equals to Y.
  511.  
  512.        ElseIf x Is Nothing AndAlso y IsNot Nothing Then
  513.            Return ComparerResult.Less ' X is less than Y.
  514.  
  515.        ElseIf x IsNot Nothing AndAlso y Is Nothing Then
  516.            Return ComparerResult.Greater ' X is greater than Y.
  517.  
  518.        End If
  519.  
  520.        ' The single variables to parse the text.
  521.        Dim SingleX, SingleY As Single
  522.  
  523.        ' Single parsing:
  524.        If Single.TryParse(x, SingleX) AndAlso Single.TryParse(y, SingleY) Then ' True and True
  525.            Return [Enum].Parse(GetType(ComparerResult),
  526.                                SingleX.CompareTo(SingleY))
  527.  
  528.        ElseIf Single.TryParse(x, SingleX) AndAlso Not Single.TryParse(y, SingleY) Then ' True and False
  529.            Return ComparerResult.Greater ' X is greater than Y.
  530.  
  531.        ElseIf Not Single.TryParse(x, SingleX) AndAlso Single.TryParse(y, SingleY) Then ' False and True
  532.            Return ComparerResult.Less ' X is less than Y.
  533.  
  534.        Else ' False and False
  535.            Return [Enum].Parse(GetType(ComparerResult),
  536.                                x.ToString.CompareTo(y.ToString))
  537.  
  538.        End If
  539.  
  540.    End Function
  541.  
  542. #End Region
  543.  
  544. End Class
  545.  
  546. #End Region
  547.  
  548. #Region " Date "
  549.  
  550. ''' <summary>
  551. ''' Performs a date comparison.
  552. ''' </summary>
  553. Public Class DateComparer : Implements IComparer
  554.  
  555. #Region " Enumerations "
  556.  
  557.    ''' <summary>
  558.    ''' Specifies a comparison result.
  559.    ''' </summary>
  560.    Public Enum ComparerResult As Integer
  561.  
  562.        ''' <summary>
  563.        ''' 'X' is equals to 'Y'.
  564.        ''' </summary>
  565.        Equals = 0I
  566.  
  567.        ''' <summary>
  568.        ''' 'X' is less than 'Y'.
  569.        ''' </summary>
  570.        Less = -1I
  571.  
  572.        ''' <summary>
  573.        ''' 'X' is greater than 'Y'.
  574.        ''' </summary>
  575.        Greater = 1I
  576.  
  577.    End Enum
  578.  
  579. #End Region
  580.  
  581. #Region " Methods "
  582.  
  583.    ''' <summary>
  584.    ''' Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
  585.    ''' </summary>
  586.    ''' <param name="x">The first object to compare.</param>
  587.    ''' <param name="y">The second object to compare.</param>
  588.    ''' <returns>
  589.    ''' A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>,
  590.    ''' 0: <paramref name="x"/> equals <paramref name="y"/>.
  591.    ''' Less than 0: <paramref name="x"/> is less than <paramref name="y"/>.
  592.    ''' Greater than 0: <paramref name="x"/> is greater than <paramref name="y"/>.
  593.    ''' </returns>
  594.    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
  595.  
  596.        ' Null parsing.
  597.        If x Is Nothing AndAlso y Is Nothing Then
  598.            Return ComparerResult.Equals ' X is equals to Y.
  599.  
  600.        ElseIf x Is Nothing AndAlso y IsNot Nothing Then
  601.            Return ComparerResult.Less ' X is less than Y.
  602.  
  603.        ElseIf x IsNot Nothing AndAlso y Is Nothing Then
  604.            Return ComparerResult.Greater ' X is greater than Y.
  605.  
  606.        End If
  607.  
  608.        ' The Date variables to parse the text.
  609.        Dim DateX, DateY As Date
  610.  
  611.        ' Date parsing:
  612.        If Date.TryParse(x, DateX) AndAlso Date.TryParse(y, DateY) Then ' True and True
  613.            Return [Enum].Parse(GetType(ComparerResult),
  614.                                DateX.CompareTo(DateY))
  615.  
  616.        ElseIf Date.TryParse(x, DateX) AndAlso Not Date.TryParse(y, DateY) Then ' True and False
  617.            Return ComparerResult.Greater ' X is greater than Y.
  618.  
  619.        ElseIf Not Date.TryParse(x, DateX) AndAlso Date.TryParse(y, DateY) Then ' False and True
  620.            Return ComparerResult.Less ' X is less than Y.
  621.  
  622.        Else ' False and False
  623.            Return [Enum].Parse(GetType(ComparerResult),
  624.                                x.ToString.CompareTo(y.ToString))
  625.  
  626.        End If
  627.  
  628.    End Function
  629.  
  630. #End Region
  631.  
  632. End Class
  633.  
  634. #End Region
  635.  
  636. #End Region
6803  Media / Multimedia / Re: Video .mp4 borroso en: 21 Agosto 2014, 10:53 am
se puede ver claro pero en una ventana que rebasa la pantalla de mi monitor, y cuando trato de reducirlo un poco para adecuarla a la pantalla la imagen se distorsiona.

¿Así que a mayor resolución menor "distorsión"?,
me parece que podría ser un problema de mala configuración del driver de salida que utilizas en el reproductor, o del renderizador que usas por defecto, o un problema de ambos.

Mi pregunta antes de proseguir, ¿tienes instalado algún pack de codecs? (te puedes imaginar mi respuesta en caso de que si que tengas instalado alguno).

Si dices que el VLC es el que menos te distoriona el video entonces ve a las opciones de la aplicación, y busca las configuraciones del driver de salida y del renderizador, aplica esa misma configuración a los reproductores que se te vean mal (en caso de que permitan configurar esos parámetros claro).

Si en el reproductor que te funciona "mal" puedes configurar el driver de salida, escoje "Direct3D", y para el renderizador, prueba con "VMR9 (modo ventana)" o lee aquí  ↠ Choosing the Right Video Renderer

Saludos!
6804  Programación / .NET (C#, VB.NET, ASP) / Re: Mis malas combinaciones :( en: 21 Agosto 2014, 10:22 am
porque no me salen los números que he puesto para combinar ?

Por esto:
Citar
Código
  1. For Num As Integer = IndexCounter To (FixedValues.Count) Step NumStep ' 1 to 30 Step 3
  2.  
  3.               Combo.Add(Num)
  4.               ...

Estás tomando el número de la variable num en lugar de tomar un item de la colección FixedValues, se puede decir que esto ha sido un fallo mio porque como ya sabes en ese ejemplo usé una secuencia ordenada del 1 al 30, así que se me pasó por alto ese detalle al desordenar la secuencia xD.

Prueba a ver si este es el resultado que quieres obtener:
Combo.Add(FixedValues(NumStep * LenCounter))
Edito: o lo que viene a ser lo mismo:

Código
  1. Combo.Add(FixedValues(Num - 1))

Explico:
Para generar la primera combinación con los números que has mostrado, daría saltos de '3' para tomar estas posiciones:
Código:
{ 1, , , 22, , , 66, , , 20, } 
+ un número aleatorio aleatorio del rango que especificaste EDITO: del rango de 'RandomValues', para dejarlo claro.

Saludos
6805  Programación / .NET (C#, VB.NET, ASP) / Re: Problema con Visual Studio 2010 en: 21 Agosto 2014, 10:01 am
¿Puedes compartir el proyecto para echarle un vistazo?, te pediría que subieses un video del problema pero creo que no sería tan util como lo primero.

Saludos!
6806  Programación / .NET (C#, VB.NET, ASP) / Re: Información en int, hex y bin dentro de un Form en: 21 Agosto 2014, 09:42 am
¿Cuál es la mejor forma de codearlo?[/b]

Pues hombre... agregar 35 controles y usar 35 event-handlers para suscribirte al mismo evento desde luego que no es lo más eficiente, se puede reducir mucho el código para que sea siendo dinámico como dijo el compañero seba123neo, pero seguiría habiendo 35 controles en la UI, hay otras formas de hacerlo de forma dinámica (como también te explicó seba123neo).

Mi consejo:

1. Utiliza solo 1 picturebox de fondo, y para todo lo demás utiliza las classes de GDI+.

2. Dibuja una rejilla del tamaño deseado sobre el picturebox, con las columnas y filas deseadas, en el evento Paint del picturebox.

3. Crea 1 Rectangle por cada sector de la rejilla, y así ya tienes una referencia de cada sector de la rejilla con su respectiva localización y tamaño a la que puedes acceder en cualquier momento.

4. En este punto ya se supone que deberías haber obtenido una coleción de los sectores de la rejilla( te sugiero añadirlos a una List(Of Rectangle) ),
    así que solo tienes que suscribirte a los eventos del Mouse (MouseMove y MouseClick) del PictureBox donde harás las operaciones necesarias (como por ejemplo especificar en que sector de la rejilla se hizo click, y el color despues de hacer click, etc), fin del problema.


Te muestro un ejemplo:



En ese ejemplo solo utilicé 1 picturebox con el fondo negro (aunque un picturebox tampoco es totalmente necesario pero facilita un poco la tarea), dibujé la rejilla con Pens, y para todo lo demás utilicé Rectangle, siguiendo los pasos que te he explicado.





No voy a mostrar todo el trabajo porque la idea es que aprendas a hacerlo pro ti mismo, y además, yo lo hice en VB.NET, peor te dejo una ayudita por si te sirve (lo puedes traducir a C# en convertidores online):

Este método lo escribí para dibujar los márgenes del grid (lo debes utilizar en el evento Paint):

Código
  1.    ' Draw Grid
  2.    ' By Elektro
  3.    '
  4.    ''' <summary>
  5.    ''' Draws a grid in the specified <see cref="System.Drawing.Graphics"/> space.
  6.    ''' </summary>
  7.    ''' <param name="g">Indicates the <see cref="System.Drawing.Graphics"/> object.</param>
  8.    ''' <param name="GridSize">Indicates the size of the grid.</param>
  9.    ''' <param name="Columns">Indicates the amount of columns to draw.</param>
  10.    ''' <param name="Rows">Indicates the amount of rows to draw.</param>
  11.    ''' <param name="ColorColumns">Indicates the columns color.</param>
  12.    ''' <param name="ColorRows">Indicates the rows color.</param>
  13.    ''' <param name="DrawBorder">If set to <c>true</c>, a border is drawn on the grid edges.</param>
  14.    ''' <param name="ColorBorder">Indicates the border color. Default value is the same color as <param ref="ColorColumns"/></param>
  15.    ''' <param name="ColorStyle">Indicates the colors <see cref="System.Drawing.Drawing2D.DashStyle"/>.</param>
  16.    ''' <exception cref="System.ArgumentException">
  17.    ''' GridSize.Width is not divisible by the specified number of columns.
  18.    ''' or
  19.    ''' GridSize.Height is not divisible by the specified number of rows.
  20.    ''' </exception>
  21.    Private Sub DrawGrid(ByVal g As Graphics,
  22.                         ByVal GridSize As Size,
  23.                         ByVal Columns As Integer,
  24.                         ByVal Rows As Integer,
  25.                         ByVal ColorColumns As Color,
  26.                         ByVal ColorRows As Color,
  27.                         Optional ByVal DrawBorder As Boolean = True,
  28.                         Optional ByVal ColorBorder As Color = Nothing,
  29.                         Optional ByVal ColorStyle As Drawing2D.DashStyle = Drawing2D.DashStyle.Solid)
  30.  
  31.        If Not (GridSize.Width Mod Columns = 0I) Then
  32.            Throw New ArgumentException(
  33.                "GridSize.Width is not divisible by the specified number of columns.",
  34.                "GridSize")
  35.            Exit Sub
  36.  
  37.        ElseIf Not (GridSize.Height Mod Rows = 0I) Then
  38.            Throw New ArgumentException(
  39.                "GridSize.Height is not divisible by the specified number of rows.",
  40.                "GridSize")
  41.            Exit Sub
  42.  
  43.        End If
  44.  
  45.        Dim SectorWidth As Integer = (GridSize.Width \ Columns)
  46.        Dim SectorHeight As Integer = (GridSize.Height \ Rows)
  47.  
  48.        Using PenRow As New Pen(ColorRows) With {.DashStyle = ColorStyle}
  49.  
  50.            Using PenCol As New Pen(ColorColumns) With {.DashStyle = ColorStyle}
  51.  
  52.                For row As Integer = 0I To GridSize.Height - 1 Step (SectorHeight)
  53.  
  54.                    For col As Integer = 0I To GridSize.Width - 1 Step SectorWidth
  55.  
  56.                        ' Draw the vertical grid-lines.
  57.                        g.DrawLine(PenCol,
  58.                                   New Point(x:=col - 1, y:=0I),
  59.                                   New Point(x:=col - 1, y:=GridSize.Height))
  60.  
  61.                    Next col
  62.  
  63.                    ' Draw the horizontal grid-lines.
  64.                    g.DrawLine(PenRow,
  65.                               New Point(x:=0I, y:=row - 1),
  66.                               New Point(x:=GridSize.Width, y:=row - 1))
  67.  
  68.                Next row
  69.  
  70.                If DrawBorder Then
  71.  
  72.                    Using PenBorder As New Pen(If(ColorBorder = Nothing, ColorColumns, ColorBorder)) With {.DashStyle = ColorStyle}
  73.  
  74.                        ' Draw the vertical left grid-line.
  75.                        g.DrawLine(PenBorder,
  76.                                   New Point(x:=0, y:=0I),
  77.                                   New Point(x:=0, y:=GridSize.Height))
  78.  
  79.                        ' Draw the vertical right grid-line.
  80.                        g.DrawLine(PenBorder,
  81.                                   New Point(x:=(GridSize.Width - 1I), y:=0I),
  82.                                   New Point(x:=(GridSize.Width - 1I), y:=GridSize.Height))
  83.  
  84.                        ' Draw the horizontal top grid-line.
  85.                        g.DrawLine(PenBorder,
  86.                                   New Point(x:=0I, y:=0I),
  87.                                   New Point(x:=GridSize.Width, y:=0I))
  88.  
  89.                        ' Draw the horizontal bottom grid-line.
  90.                        g.DrawLine(PenBorder,
  91.                                   New Point(x:=0I, y:=(GridSize.Height - 1I)),
  92.                                   New Point(x:=GridSize.Width, y:=(GridSize.Height - 1I)))
  93.                    End Using ' PenBorder
  94.  
  95.                End If ' DrawBorder
  96.  
  97.            End Using '  PenCol
  98.  
  99.        End Using ' PenRow
  100.  
  101.    End Sub


Y este método lo escribí para obtener los rectangles de la rejilla:

Código
  1.    ' Get Grid
  2.    ' By Elektro
  3.    '
  4.    ''' <summary>
  5.    ''' Calculates the drawing of a grid with the specified size,
  6.    ''' and returns a<see cref="List(Of Rectangle)"/> that contains the grid-sector specifications.
  7.    ''' </summary>
  8.    ''' <param name="GridSize">Indicates the grid size.</param>
  9.    ''' <param name="Columns">Indicates the amount of columns.</param>
  10.    ''' <param name="Rows">Indicates the amount of rows.</param>
  11.    ''' <returns>A <see cref="List(Of Rectangle)"/> that contains the grid-sector specifications.</returns>
  12.    ''' <exception cref="System.ArgumentException">
  13.    ''' GridSize.Width is not divisible by the specified number of columns.
  14.    ''' or
  15.    ''' GridSize.Height is not divisible by the specified number of rows.
  16.    ''' </exception>
  17.    Private Function GetGrid(ByVal GridSize As Size,
  18.                             ByVal Columns As Integer,
  19.                             ByVal Rows As Integer) As List(Of Rectangle)
  20.  
  21.        If Not (GridSize.Width Mod Columns = 0I) Then
  22.            Throw New ArgumentException(
  23.                "GridSize.Width is not divisible by the specified number of columns.",
  24.                "GridSize")
  25.            Return Nothing
  26.  
  27.        ElseIf Not (GridSize.Height Mod Rows = 0I) Then
  28.            Throw New ArgumentException(
  29.                "GridSize.Height is not divisible by the specified number of rows.",
  30.                "GridSize")
  31.            Return Nothing
  32.  
  33.        End If
  34.  
  35.        Dim Sectors As New List(Of Rectangle)
  36.        Dim SectorWidth As Integer = GridSize.Width \ Columns
  37.        Dim SectorHeight As Integer = GridSize.Height \ Rows
  38.  
  39.        For row As Integer = 0I To GridSize.Height - 1 Step (SectorHeight)
  40.  
  41.            For col As Integer = 0I To GridSize.Width - 1 Step SectorWidth
  42.  
  43.                Sectors.Add(New Rectangle(col, row, SectorWidth, SectorHeight))
  44.  
  45.            Next col
  46.  
  47.        Next row
  48.  
  49.        Return Sectors
  50.  
  51.    End Function


EDITO2:

bueno voy a mostrate el resto del código porque total lo hice para ayudarte con el problema y ya no me sirve para nada esto así que antes de tirarlo te lo enseño xD, espero que te sirva.

( esta parte del code lo desarrollé en poco tiempo, está bastante sucio el código y se puede mejorar mucho, pero sirve para hacerse una idea )

Código
  1.    Public Property currentsector As Integer = 0
  2.    Public Property currentcolor As Color = Color.Gray
  3.  
  4.    Public ReadOnly Property GridSectors As List(Of Rectangle)
  5.        Get
  6.            Return Me.GetGrid(GridSize:=PictureBox1.ClientRectangle.Size, Columns:=5, Rows:=5)
  7.        End Get
  8.    End Property
  9.  
  10.    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Shown
  11.  
  12.        Label1.Text = "Sectors: " & GridSectors.Count
  13.  
  14.    End Sub
  15.  
  16.    Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _
  17.    Handles PictureBox1.Paint
  18.  
  19.  
  20.        Me.DrawGrid(g:=e.Graphics,
  21.                    GridSize:=sender.ClientRectangle.Size,
  22.                    Columns:=5,
  23.                    Rows:=5,
  24.                    ColorColumns:=Color.YellowGreen,
  25.                    ColorRows:=Color.YellowGreen,
  26.                    DrawBorder:=True,
  27.                    ColorBorder:=Nothing,
  28.                    ColorStyle:=Drawing2D.DashStyle.Solid)
  29.  
  30.    End Sub
  31.  
  32.    Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
  33.  
  34.        Dim Sectors As List(Of Rectangle) = Me.GridSectors
  35.  
  36.        For X As Integer = 0I To (Sectors.Count - 1I)
  37.  
  38.            If Sectors(X).Contains(sender.PointToClient(MousePosition)) Then
  39.  
  40.                Dim myBrush As New SolidBrush(currentcolor)
  41.  
  42.                Using formGraphics As Graphics = sender.CreateGraphics()
  43.  
  44.                    formGraphics.FillRectangle(myBrush, New Rectangle(Sectors(X).X + 1, Sectors(X).Y + 1, Sectors(X).Width - 2, Sectors(X).Height - 2))
  45.                    myBrush.Dispose()
  46.  
  47.                End Using ' formGraphics
  48.                currentsector = X + 1
  49.                Label2.Text = "Current sector: " & currentsector
  50.  
  51.            Else
  52.                Dim myBrush As New SolidBrush(Color.Black)
  53.  
  54.                Using formGraphics As Graphics = sender.CreateGraphics()
  55.  
  56.                    formGraphics.FillRectangle(myBrush, New Rectangle(Sectors(X).X + 1, Sectors(X).Y + 1, Sectors(X).Width - 2, Sectors(X).Height - 2))
  57.                    myBrush.Dispose()
  58.  
  59.                End Using ' formGraphics
  60.            End If ' Sectors(X).Contains(...)
  61.  
  62.        Next X
  63.  
  64.    End Sub
  65.  
  66.    Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.MouseDown
  67.  
  68.        Label3.Text = "Last Sector Clicked: " & currentsector
  69.  
  70.        '  Dim sector As Rectangle = Me.GridSectors(currentsector - 1)
  71.        currentcolor = Color.Red
  72.        PictureBox1.Cursor = Cursors.Hand
  73.        PictureBox1.Update()
  74.  
  75.        'Dim myBrush As New SolidBrush(Color.Red)
  76.  
  77.        'Using formGraphics As Graphics = PictureBox1.CreateGraphics()
  78.  
  79.        '    formGraphics.FillRectangle(myBrush, New Rectangle(sector.X + 1, sector.Y + 1, sector.Width - 2, sector.Height - 2))
  80.        '    myBrush.Dispose()
  81.  
  82.        'End Using ' formGraphics
  83.  
  84.    End Sub
  85.  
  86.    Private Sub PictureBox1_Clic(sender As Object, e As EventArgs) Handles PictureBox1.MouseUp
  87.        Label3.Text = "Last Sector Clicked: " & currentsector
  88.  
  89.        '  Dim sector As Rectangle = Me.GridSectors(currentsector - 1)
  90.        currentcolor = Color.Gray
  91.        PictureBox1.Cursor = Cursors.Default
  92.        PictureBox1.Update()
  93.  
  94.        'Dim myBrush As New SolidBrush(Color.Red)
  95.  
  96.        'Using formGraphics As Graphics = PictureBox1.CreateGraphics()
  97.  
  98.        '    formGraphics.FillRectangle(myBrush, New Rectangle(sector.X + 1, sector.Y + 1, sector.Width - 2, sector.Height - 2))
  99.        '    myBrush.Dispose()
  100.  
  101.        'End Using ' formGraphics
  102.  
  103.    End Sub




EDITO1:


Fijándome justo la imagen de arriba, al pinchar los pictureBox quiero que aparezcan en tiempo real los resultados en Decimales, Hexadecimales y Binarios.

El tiempo real quiero decir, que desde que pulse un pictureBox, se actualiza los datos dentro de los textBox inficado arriba.

Con usar timer de 0.1 segundo funciona en vez de usar un botón para actualizar.

Espero que se entienda lo que quiero hacer. Esta parte si que no me sale.

Lo siento creo que no te entendí muy bien, ¿que problema tienes actualmente a la hora de actualizar los valores de cada control?.

Si vas a utilizar tropecientos pictureboxes entonces deberías suscribirte al evento Click como te explicó seba123neo, y una vez pulses cualquier picturebox actualizaríass los valores (de forma interna) y los imprimirías en los textboxes, ¿cual es el problema?

Saludos
6807  Programación / Scripting / Re: [AYUDA][PYTHON] Leer y guardar archivos .exe de forma hexadecimal en python??? en: 21 Agosto 2014, 08:44 am
Todo lo que necesitas para leer/escribir bytes en un stream lo tienes en el módulo 'IO': https://docs.python.org/2/library/io.html

Ejemplo:
Código:
>>> f = open('/tmp/IMG_5982.JPG', 'rb')
>>> data = f.read(10)
>>> data
'\x00\x00II*\x00\x08\x00\x00\x00'

Código:
>>> data[2]
'I'

Las secuencias de Bytes en Python se representan como strings, como puedes ver.

Pero puedes utilizar el método Ord() o Bin() para obtener una representación Decimal o Binaria respectivamente

Código:
>>> ord(data[2])
73

>>> hex(ord(data[2]))
'0x49'

>>> bin(ord(data[2]))
'0b1001001'

Tienes muchos ejemplos de todo ello en Google.

Saludos!
6808  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 20 Agosto 2014, 02:06 am
He escrito este ejemplo para mostrar como se puede compartir un espacio de memoria que puede ser leido por diferentes aplicaciones:



Esta sería la aplicación número 1, creen un nuevo proyecto, copien y compilen este Form:

Código
  1. ' Example of sharing memory across different running applications.
  2. ' By Elektro
  3. '
  4. ' *************************
  5. ' This is the Application 1
  6. ' *************************
  7.  
  8. #Region " Imports "
  9.  
  10. Imports System.IO.MemoryMappedFiles
  11.  
  12. #End Region
  13.  
  14. #Region " Application 2 "
  15.  
  16. ''' <summary>
  17. ''' Class MemoryMappedFile_Form1.
  18. ''' This should be the Class used to compile our first application.
  19. ''' </summary>
  20. Public Class MemoryMappedFile_Form1
  21.  
  22.    ' The controls to create on execution-time.
  23.    Dim WithEvents btMakeFile As New Button ' Writes the memory.
  24.    Dim WithEvents btReadFile As New Button ' Reads the memory.
  25.    Dim tbMessage As New TextBox ' Determines the string to map into memory.
  26.    Dim tbReceptor As New TextBox ' Print the memory read's result.
  27.    Dim lbInfoButtons As New Label ' Informs the user with a usage hint for the buttons.
  28.    Dim lbInfotbMessage As New Label ' Informs the user with a usage hint for 'tbMessage'.
  29.  
  30.    ''' <summary>
  31.    ''' Indicates the name of our memory-file.
  32.    ''' </summary>
  33.    Private ReadOnly MemoryName As String = "My Memory-File Name"
  34.  
  35.    ''' <summary>
  36.    ''' Indicates the memory buffersize to store the <see cref="MemoryName"/>, in bytes.
  37.    ''' </summary>
  38.    Private ReadOnly MemoryBufferSize As Integer = 1024I
  39.  
  40.    ''' <summary>
  41.    ''' Indicates the string to map in memory.
  42.    ''' </summary>
  43.    Private ReadOnly Property strMessage As String
  44.        Get
  45.            Return tbMessage.Text
  46.        End Get
  47.    End Property
  48.  
  49.    ''' <summary>
  50.    ''' Initializes a new instance of the <see cref="MemoryMappedFile_Form1"/> class.
  51.    ''' </summary>
  52.    Public Sub New()
  53.  
  54.        ' This call is required by the designer.
  55.        InitializeComponent()
  56.  
  57.        ' Set the properties of the controls.
  58.        With lbInfotbMessage
  59.            .Location = New Point(20, 10)
  60.            .Text = "Type in this TextBox the message to write in memory:"
  61.            .AutoSize = True
  62.            ' .Size = tbReceptor.Size
  63.        End With
  64.        With tbMessage
  65.            .Text = "Hello world from application one!"
  66.            .Location = New Point(20, 30)
  67.            .Size = New Size(310, Me.tbMessage.Height)
  68.        End With
  69.        With btMakeFile
  70.            .Text = "Write Memory"
  71.            .Size = New Size(130, 45)
  72.            .Location = New Point(20, 50)
  73.        End With
  74.        With btReadFile
  75.            .Text = "Read Memory"
  76.            .Size = New Size(130, 45)
  77.            .Location = New Point(200, 50)
  78.        End With
  79.        With tbReceptor
  80.            .Location = New Point(20, 130)
  81.            .Size = New Size(310, 100)
  82.            .Multiline = True
  83.        End With
  84.        With lbInfoButtons
  85.            .Location = New Point(tbReceptor.Location.X, tbReceptor.Location.Y - 30)
  86.            .Text = "Press '" & btMakeFile.Text & "' button to create the memory file, that memory can be read from both applications."
  87.            .AutoSize = False
  88.            .Size = tbReceptor.Size
  89.        End With
  90.  
  91.        ' Set the Form properties.
  92.        With Me
  93.            .Text = "Application 1"
  94.            .Size = New Size(365, 300)
  95.            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
  96.            .MaximizeBox = False
  97.            .StartPosition = FormStartPosition.CenterScreen
  98.        End With
  99.  
  100.        ' Add the controls on the UI.
  101.        Me.Controls.AddRange({lbInfotbMessage, tbMessage, btMakeFile, btReadFile, tbReceptor, lbInfoButtons})
  102.  
  103.    End Sub
  104.  
  105.    ''' <summary>
  106.    ''' Writes a byte sequence into a <see cref="MemoryMappedFile"/>.
  107.    ''' </summary>
  108.    ''' <param name="Name">Indicates the name to assign the <see cref="MemoryMappedFile"/>.</param>
  109.    ''' <param name="BufferLength">Indicates the <see cref="MemoryMappedFile"/> buffer-length to write in.</param>
  110.    ''' <param name="Data">Indicates the byte-data to write inside the <see cref="MemoryMappedFile"/>.</param>
  111.    Private Sub MakeMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer, ByVal Data As Byte())
  112.  
  113.        ' Create or open the memory-mapped file.
  114.        Dim MessageFile As MemoryMappedFile =
  115.            MemoryMappedFile.CreateOrOpen(Name, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)
  116.  
  117.        ' Write the byte-sequence into memory.
  118.        Using Writer As MemoryMappedViewAccessor =
  119.            MessageFile.CreateViewAccessor(0L, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)
  120.  
  121.            ' Firstly fill with null all the buffer.
  122.            Writer.WriteArray(Of Byte)(0L, System.Text.Encoding.ASCII.GetBytes(New String(Nothing, Me.MemoryBufferSize)), 0I, Me.MemoryBufferSize)
  123.  
  124.            ' Secondly write the byte-data.
  125.            Writer.WriteArray(Of Byte)(0L, Data, 0I, Data.Length)
  126.  
  127.        End Using ' Writer
  128.  
  129.    End Sub
  130.  
  131.    ''' <summary>
  132.    ''' Reads a byte-sequence from a <see cref="MemoryMappedFile"/>.
  133.    ''' </summary>
  134.    ''' <param name="Name">Indicates an existing <see cref="MemoryMappedFile"/> assigned name.</param>
  135.    ''' <param name="BufferLength">The buffer-length to read in.</param>
  136.    ''' <returns>System.Byte().</returns>
  137.    Private Function ReadMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer) As Byte()
  138.  
  139.        Try
  140.            Using MemoryFile As MemoryMappedFile =
  141.                MemoryMappedFile.OpenExisting(Name, MemoryMappedFileRights.Read)
  142.  
  143.                Using Reader As MemoryMappedViewAccessor =
  144.                    MemoryFile.CreateViewAccessor(0L, BufferLength, MemoryMappedFileAccess.Read)
  145.  
  146.                    Dim ReadBytes As Byte() = New Byte(BufferLength - 1I) {}
  147.                    Reader.ReadArray(Of Byte)(0L, ReadBytes, 0I, ReadBytes.Length)
  148.                    Return ReadBytes
  149.  
  150.                End Using ' Reader
  151.  
  152.            End Using ' MemoryFile
  153.  
  154.        Catch ex As IO.FileNotFoundException
  155.            Throw
  156.            Return Nothing
  157.  
  158.        End Try
  159.  
  160.    End Function
  161.  
  162.    ''' <summary>
  163.    ''' Handles the 'Click' event of the 'btMakeFile' control.
  164.    ''' </summary>
  165.    Private Sub btMakeFile_Click() Handles btMakeFile.Click
  166.  
  167.        ' Get the byte-data to create the memory-mapped file.
  168.        Dim WriteData As Byte() = System.Text.Encoding.ASCII.GetBytes(Me.strMessage)
  169.  
  170.        ' Create the memory-mapped file.
  171.        Me.MakeMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize, Data:=WriteData)
  172.  
  173.    End Sub
  174.  
  175.    ''' <summary>
  176.    ''' Handles the 'Click' event of the 'btReadFile' control.
  177.    ''' </summary>
  178.    Private Sub btReadFile_Click() Handles btReadFile.Click
  179.  
  180.  
  181.        Dim ReadBytes As Byte()
  182.  
  183.        Try ' Read the byte-sequence from memory.
  184.            ReadBytes = ReadMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize)
  185.  
  186.        Catch ex As IO.FileNotFoundException
  187.            Me.tbReceptor.Text = "Memory-mapped file does not exist."
  188.            Exit Sub
  189.  
  190.        End Try
  191.  
  192.        ' Convert the bytes to String.
  193.        Dim Message As String = System.Text.Encoding.ASCII.GetString(ReadBytes.ToArray)
  194.  
  195.        ' Remove null chars (leading zero-bytes)
  196.        Message = Message.Trim({ControlChars.NullChar})
  197.  
  198.        ' Print the message.
  199.        tbReceptor.Text = Message
  200.  
  201.    End Sub
  202.  
  203. End Class
  204.  
  205. #End Region

Esta sería la aplicación número 2, creen un nuevo proyecto, copien y compilen este Form:

Código
  1. ' Example of sharing memory across different running applications.
  2. ' By Elektro
  3. '
  4. ' *************************
  5. ' This is the Application 2
  6. ' *************************
  7.  
  8. #Region " Imports "
  9.  
  10. Imports System.IO.MemoryMappedFiles
  11.  
  12. #End Region
  13.  
  14. #Region " Application 2 "
  15.  
  16. ''' <summary>
  17. ''' Class MemoryMappedFile_Form2.
  18. ''' This should be the Class used to compile our first application.
  19. ''' </summary>
  20. Public Class MemoryMappedFile_Form2
  21.  
  22.    ' The controls to create on execution-time.
  23.    Dim WithEvents btMakeFile As New Button ' Writes the memory.
  24.    Dim WithEvents btReadFile As New Button ' Reads the memory.
  25.    Dim tbMessage As New TextBox ' Determines the string to map into memory.
  26.    Dim tbReceptor As New TextBox ' Print the memory read's result.
  27.    Dim lbInfoButtons As New Label ' Informs the user with a usage hint for the buttons.
  28.    Dim lbInfotbMessage As New Label ' Informs the user with a usage hint for 'tbMessage'.
  29.  
  30.    ''' <summary>
  31.    ''' Indicates the name of our memory-file.
  32.    ''' </summary>
  33.    Private ReadOnly MemoryName As String = "My Memory-File Name"
  34.  
  35.    ''' <summary>
  36.    ''' Indicates the memory buffersize to store the <see cref="MemoryName"/>, in bytes.
  37.    ''' </summary>
  38.    Private ReadOnly MemoryBufferSize As Integer = 1024I
  39.  
  40.    ''' <summary>
  41.    ''' Indicates the string to map in memory.
  42.    ''' </summary>
  43.    Private ReadOnly Property strMessage As String
  44.        Get
  45.            Return tbMessage.Text
  46.        End Get
  47.    End Property
  48.  
  49.    ''' <summary>
  50.    ''' Initializes a new instance of the <see cref="MemoryMappedFile_Form2"/> class.
  51.    ''' </summary>
  52.    Public Sub New()
  53.  
  54.        ' This call is required by the designer.
  55.        InitializeComponent()
  56.  
  57.        ' Set the properties of the controls.
  58.        With lbInfotbMessage
  59.            .Location = New Point(20, 10)
  60.            .Text = "Type in this TextBox the message to write in memory:"
  61.            .AutoSize = True
  62.            ' .Size = tbReceptor.Size
  63.        End With
  64.        With tbMessage
  65.            .Text = "Hello world from application two!"
  66.            .Location = New Point(20, 30)
  67.            .Size = New Size(310, Me.tbMessage.Height)
  68.        End With
  69.        With btMakeFile
  70.            .Text = "Write Memory"
  71.            .Size = New Size(130, 45)
  72.            .Location = New Point(20, 50)
  73.        End With
  74.        With btReadFile
  75.            .Text = "Read Memory"
  76.            .Size = New Size(130, 45)
  77.            .Location = New Point(200, 50)
  78.        End With
  79.        With tbReceptor
  80.            .Location = New Point(20, 130)
  81.            .Size = New Size(310, 100)
  82.            .Multiline = True
  83.        End With
  84.        With lbInfoButtons
  85.            .Location = New Point(tbReceptor.Location.X, tbReceptor.Location.Y - 30)
  86.            .Text = "Press '" & btMakeFile.Text & "' button to create the memory file, that memory can be read from both applications."
  87.            .AutoSize = False
  88.            .Size = tbReceptor.Size
  89.        End With
  90.  
  91.        ' Set the Form properties.
  92.        With Me
  93.            .Text = "Application 2"
  94.            .Size = New Size(365, 300)
  95.            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
  96.            .MaximizeBox = False
  97.            .StartPosition = FormStartPosition.CenterScreen
  98.        End With
  99.  
  100.        ' Add the controls on the UI.
  101.        Me.Controls.AddRange({lbInfotbMessage, tbMessage, btMakeFile, btReadFile, tbReceptor, lbInfoButtons})
  102.  
  103.    End Sub
  104.  
  105.    ''' <summary>
  106.    ''' Writes a byte sequence into a <see cref="MemoryMappedFile"/>.
  107.    ''' </summary>
  108.    ''' <param name="Name">Indicates the name to assign the <see cref="MemoryMappedFile"/>.</param>
  109.    ''' <param name="BufferLength">Indicates the <see cref="MemoryMappedFile"/> buffer-length to write in.</param>
  110.    ''' <param name="Data">Indicates the byte-data to write inside the <see cref="MemoryMappedFile"/>.</param>
  111.    Private Sub MakeMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer, ByVal Data As Byte())
  112.  
  113.        ' Create or open the memory-mapped file.
  114.        Dim MessageFile As MemoryMappedFile =
  115.            MemoryMappedFile.CreateOrOpen(Name, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)
  116.  
  117.        ' Write the byte-sequence into memory.
  118.        Using Writer As MemoryMappedViewAccessor =
  119.            MessageFile.CreateViewAccessor(0L, Me.MemoryBufferSize, MemoryMappedFileAccess.ReadWrite)
  120.  
  121.            ' Firstly fill with null all the buffer.
  122.            Writer.WriteArray(Of Byte)(0L, System.Text.Encoding.ASCII.GetBytes(New String(Nothing, Me.MemoryBufferSize)), 0I, Me.MemoryBufferSize)
  123.  
  124.            ' Secondly write the byte-data.
  125.            Writer.WriteArray(Of Byte)(0L, Data, 0I, Data.Length)
  126.  
  127.        End Using ' Writer
  128.  
  129.    End Sub
  130.  
  131.    ''' <summary>
  132.    ''' Reads a byte-sequence from a <see cref="MemoryMappedFile"/>.
  133.    ''' </summary>
  134.    ''' <param name="Name">Indicates an existing <see cref="MemoryMappedFile"/> assigned name.</param>
  135.    ''' <param name="BufferLength">The buffer-length to read in.</param>
  136.    ''' <returns>System.Byte().</returns>
  137.    Private Function ReadMemoryMappedFile(ByVal Name As String, ByVal BufferLength As Integer) As Byte()
  138.  
  139.        Try
  140.            Using MemoryFile As MemoryMappedFile =
  141.                MemoryMappedFile.OpenExisting(Name, MemoryMappedFileRights.Read)
  142.  
  143.                Using Reader As MemoryMappedViewAccessor =
  144.                    MemoryFile.CreateViewAccessor(0L, BufferLength, MemoryMappedFileAccess.Read)
  145.  
  146.                    Dim ReadBytes As Byte() = New Byte(BufferLength - 1I) {}
  147.                    Reader.ReadArray(Of Byte)(0L, ReadBytes, 0I, ReadBytes.Length)
  148.                    Return ReadBytes
  149.  
  150.                End Using ' Reader
  151.  
  152.            End Using ' MemoryFile
  153.  
  154.        Catch ex As IO.FileNotFoundException
  155.            Throw
  156.            Return Nothing
  157.  
  158.        End Try
  159.  
  160.    End Function
  161.  
  162.    ''' <summary>
  163.    ''' Handles the 'Click' event of the 'btMakeFile' control.
  164.    ''' </summary>
  165.    Private Sub btMakeFile_Click() Handles btMakeFile.Click
  166.  
  167.        ' Get the byte-data to create the memory-mapped file.
  168.        Dim WriteData As Byte() = System.Text.Encoding.ASCII.GetBytes(Me.strMessage)
  169.  
  170.        ' Create the memory-mapped file.
  171.        Me.MakeMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize, Data:=WriteData)
  172.  
  173.    End Sub
  174.  
  175.    ''' <summary>
  176.    ''' Handles the 'Click' event of the 'btReadFile' control.
  177.    ''' </summary>
  178.    Private Sub btReadFile_Click() Handles btReadFile.Click
  179.  
  180.  
  181.        Dim ReadBytes As Byte()
  182.  
  183.        Try ' Read the byte-sequence from memory.
  184.            ReadBytes = ReadMemoryMappedFile(Name:=Me.MemoryName, BufferLength:=Me.MemoryBufferSize)
  185.  
  186.        Catch ex As IO.FileNotFoundException
  187.            Me.tbReceptor.Text = "Memory-mapped file does not exist."
  188.            Exit Sub
  189.  
  190.        End Try
  191.  
  192.        ' Convert the bytes to String.
  193.        Dim Message As String = System.Text.Encoding.ASCII.GetString(ReadBytes.ToArray)
  194.  
  195.        ' Remove null chars (leading zero-bytes)
  196.        Message = Message.Trim({ControlChars.NullChar})
  197.  
  198.        ' Print the message.
  199.        tbReceptor.Text = Message
  200.  
  201.    End Sub
  202.  
  203. End Class
  204.  
  205. #End Region

Ahora ya solo tienen que ejecutar ambas aplicaciones para testear.

Saludos!
6809  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 19 Agosto 2014, 22:06 pm
Un ejemplo de uso de la librería MagicGraphics: http://www.codeproject.com/Articles/19188/Magic-Graphics







Escribí este Form para jugar un poco con la funcionalidad de esta librería, la verdad es que es muy sencillo.



Código
  1. Public Class MagicGraphics_Test
  2.  
  3.    Private WithEvents RotationTimer As New Timer With {.Enabled = True, .Interval = 25}
  4.  
  5.    Dim SC As MagicGraphics.ShapeContainer
  6.  
  7.    Private Sub Tst_Shown() Handles MyBase.Shown
  8.  
  9.        SC = New MagicGraphics.ShapeContainer(PictureBox1.CreateGraphics, PictureBox1.Width, PictureBox1.Height, Color.Black, PictureBox1.Image)
  10.        PictureBox1.Image = SC.BMP
  11.        SC.AutoFlush = False
  12.  
  13.        Dim Sq As New MagicGraphics.Rectangle(New Pen(Color.Black, 3), Brushes.Aqua, 60, 20, 50, 50)
  14.        Sq.FillingBrush = New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(60, 0), Color.Yellow, Color.Red)
  15.        SC.AddShape(Sq)
  16.        Dim El As New MagicGraphics.Ellipse(New Pen(Color.Black, 3), Brushes.Olive, 60, 88, 50, 71)
  17.        El.FillingBrush = New Drawing2D.LinearGradientBrush(New Point(0, 0), New Point(30, 0), Color.Red, Color.SteelBlue)
  18.        SC.AddShape(El)
  19.  
  20.        RotationTimer.Start()
  21.  
  22.    End Sub
  23.  
  24.  
  25.    Private Sub RotationTimer_Tick() Handles RotationTimer.Tick
  26.  
  27.        Static Direction As Integer = 1I ' 0 = Left, 1 = Right
  28.  
  29.        For X As Integer = 0I To (SC.ShapesL.Count - 1)
  30.  
  31.            Dim shp As MagicGraphics.Shape = SC.ShapesL(X)
  32.  
  33.            shp.Rotate(-8)
  34.  
  35.            If shp.Location.X > (PictureBox1.Width - shp.Width) Then
  36.                Direction = 1I ' Right
  37.  
  38.            ElseIf shp.Location.X < PictureBox1.Location.X Then
  39.                Direction = 0I ' Left
  40.  
  41.            End If
  42.  
  43.            If Direction = 0 Then
  44.                shp.Move(shp.Location.X + 2, shp.Location.Y)
  45.  
  46.            Else
  47.                shp.Move(shp.Location.X - 2, shp.Location.Y)
  48.  
  49.            End If
  50.  
  51.            ' Debug.WriteLine(String.Format("Shape {0} Rotation: {1}", CStr(X), shp.Rotation))
  52.  
  53.        Next X
  54.  
  55.        SC.Flush()
  56.  
  57.    End Sub
  58.  
  59. End Class
  60.  
6810  Programación / .NET (C#, VB.NET, ASP) / Re: Mis malas combinaciones :( en: 19 Agosto 2014, 13:49 pm
Mil gracias de nuevo ahora si pude hacerlo funcionar :)

Bien aca donde me pones esto , es lo debería de cambiar por mi variable " result " que es la que tiene los números después de efectuada la operación que hago en mi programa ?

Código
  1. ReadOnly FixedValues As Integer() = {1, 5, 19, 22, 34, 55, 66, 88, 99, etc...}

¿A cual de las miles de variables que bautizaste con el nombre de "Result" te refieres? :P

Supongo que si, en la variable FixedValues debes especificarle los numeros que se tomarán para hacer las combinaciones, en tu ejemplo pusiste del 1 al 30, no se si harás eso con la variable "result" que mencionas, pero creo que ya te hiciste una idea de lo que debe ir en esa variable FixedValues (valores fijos).

por lo demas funciona como queria

Me alegro de oir eso

PD: Por si acaso te recuerdo que para ordenar de mayor a menor lo tienes facil usando una LINQ-query:
Código
  1. dim values as integer() = (from n as integer in TUSNUMEROS order by n ascending).toarray

o el método Sort, en una lista.

Saludos!
Páginas: 1 ... 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 [681] 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines