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

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


  Mostrar Mensajes
Páginas: 1 2 3 4 5 [6] 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ... 32
51  Programación / Programación Visual Basic / Re: Ejecutar un archivo seleccionado desde resource en: 16 Junio 2016, 17:09 pm
Hola

Deberías especificar si lo quieres para VB6 o VB.NET


En VB6 puedes usar esta función para extraer el archivo:

Código
  1. Public Function CrearArchivoBinario(strPath As String, strNameFile As String, idRes As Variant, TypeRes As String)
  2. On Error GoTo EvitarError
  3. Dim Path As String
  4. Dim numFile As Integer
  5. Dim aDatos() As Byte
  6. numFile = FreeFile
  7.    Path = strPath & "\" & strNameFile
  8.  
  9.    ' lee los datos en el array de bytes
  10.    aDatos = LoadResData(idRes, TypeRes)
  11.  
  12.    ' abre un archivo para escribir los datos en modo binario
  13.    Open Path For Binary Access Write As #numFile
  14.  
  15.    ' escribe el array de bytes para
  16.    Put #numFile, , aDatos
  17.    ' cierra el fichero
  18.    Close
  19.    'MsgBox "Datos guardados con éxito", vbInformation, "Información"
  20. EvitarError:
  21. If Err.Number <> vbNull Then
  22. MsgBox Err.Description, vbCritical, "Error"
  23. End If
  24. End Function
  25.  




Y la forma de usarlo es esta:

Código:
CrearArchivoBinario DIRECTORIO, "ARCHIVO", ID, "TIPO"

Ejemplo:

Código:
CrearArchivoBinario "C:\MyBinFile", "Aplicación.exe", 101, "CUSTOM"


NOTA: El directorio debe existir. Esta función no crea directorios. Por ejemplo si pones "C:\MyBinFile" y la carpeta "MyBinFile" no existe se produce un error.


Para ejecutarlo puedes usar Shell()

s2s

52  Programación / .NET (C#, VB.NET, ASP) / Re: Terminar evento MouseDown con el botón del ratón pulsado en: 16 Junio 2016, 02:34 am
Hola Lekim.

Si me equivoco en mis suposiciones, corrígeme, pero según leo en ese comentario das a entender que lo que realmente quieres hacer (ahora) es conseguir que se dispare el evento MouseDown en un control mientras mantienes presionado el botón izquierdo del mouse sobre el Form y arrastras el puntero hasta ese control. ¿es así?.


No no es eso Elektro, pero parece que lo que has puesto puede servir, me lo voy a mirar.



Pero bueno que ya está hecho y tampoco es tanto código.
- Es código administrado
- He reducido el código considerablemente
- No tiene errores
- Es puro Net
- 100% cosecha propia

¿Cuál es la queja? XD

Lo que has puesto es a la inversa en un principio quería enviar el mensaje  WM_LBUTTONUP y Down  desde un evento. Usé Mouse_Event para hacerlo, aunque ahora veo por lo que as posteado que también podía haber usado SendMessage. Pero era un parche por no poder capturar el índice del label en el cual estaba posado el cursor con el botón del Mouse apretado al arrastrarlo por los labels.  Si reproduces el útlimo código que he posteado lo verás.


Y si has usado mi piano pues es el efecto de arrastrar el dedo por las teclas. Apretas y arrastras, suena cada nota por la que va pasando el dedo, a la vez que se apagan por las que ya a pasado y a la vez que se cambia el color de la tacla en la que se encuentra el dedo (el puntero), se pone la tecla de nuevo blanca la que ya no tiene el dedo (el puntero) y todo sin soltar. Facilísimo!!!

53  Programación / .NET (C#, VB.NET, ASP) / Re: Terminar evento MouseDown con el botón del ratón pulsado en: 16 Junio 2016, 01:13 am
Hola

Bueno, pues ya lo he hecho y sin código no administrado. Ahora saldrá el listo que dirá, pero si es muy fácil no hace falta hacer tanta historia...

Cuando he preguntado y nadie me resolvía la papeleta. Incluso en otro foro (en inglés) un usuario me ha puesto de los nervios porque no hacía más que decirme que era muy fácil, que usara MouseEnter, MouseLeave. Yo le dije que estos eventos no fucionan cuando arrastras el puntero con el bóton del ratón presionado, que no devuelven el índice del control donde se encuentra el puntero. De nuevo me contesta - ten encuenta el OOP, bla, bla, bla...-, jolines si es tan fácil teclea un poco y lo pones maldito hijo de la gran....   Igual se penseava que es sólo el clic. Pero si es que hasta le puse imágenes de demostración.

Total que está hecho. No fuerzo la cancelación del evento, como hacía con Mouse_Event que era una alternativa para hacer lo que quería.

Lo he hecho usando lógica matemática, mediante un algoritmo obtengo el índice del Label en el que se encuentra el cursor, estando el botón pulsado y arrastrandose a través del array de Labels. Que repito, cuando haces esto los eventos se estancan en el primer label donde se ha hecho MouseDown y no devuelven una porra. Como demuestra este gif animado





El algoritmo:

Código:
-[(-Index)-int(X/20)]

Donde:
Index=  Indice actual (que no cambia hasta que no se colorea un nuevo label, por eso se obtiene en el evento Paint)
X = Posición X del cursor dentro del formulario
20 = Ancho del Label.


Código
  1. Option Strict On
  2. Imports System.Runtime.InteropServices
  3.  
  4.  
  5. Public Class Form1
  6.    Dim lblkey(5) As Label
  7.    Dim index As Integer
  8.  
  9.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  10.        Dim locLBL As New Point(10, 10)
  11.        Dim inc As Integer
  12.        For I As Integer = 0 To 5
  13.            lblkey(I) = New Label
  14.            lblkey(I).Size = CType(New Point(20, 100), Drawing.Size)
  15.            lblkey(I).BorderStyle = BorderStyle.FixedSingle
  16.            lblkey(I).Location = New Point(locLBL.X + inc, locLBL.Y)
  17.            Me.Controls.Add(lblkey(I))
  18.            inc += 19
  19.        Next
  20.        For I As Integer = 0 To 5
  21.            AddHandler lblkey(I).MouseDown, AddressOf lblkey_MouseDown
  22.            AddHandler lblkey(I).MouseUp, AddressOf lblkey_MouseUp
  23.            AddHandler lblkey(I).MouseMove, AddressOf lblkey_MouseMove
  24.            AddHandler lblkey(I).Paint, AddressOf lblkey_Paint
  25.        Next
  26.  
  27.    End Sub
  28.    Private Sub lblkey_Paint(ByVal sender As Object, ByVal e As System.EventArgs)
  29.        index = Array.IndexOf(lblkey, sender)
  30.    End Sub
  31.  
  32.    Private Sub lblkey_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  33.        Dim lblPoint As New  _
  34.        Point(lblkey(index).PointToClient(Cursor.Position).X, _
  35.           lblkey(index).PointToClient(Cursor.Position).Y)
  36.  
  37.        If e.Button = System.Windows.Forms.MouseButtons.Left Then
  38.            Dim newIndex As Double = - ((- index) - Conversion.Int(lblPoint.X / 20))
  39.            Try
  40.                Dim AllIndexs As New List(Of Integer)({0, 1, 2, 3, 4, 5})
  41.                AllIndexs.Remove(CInt(newIndex))
  42.                For Each El As Integer In AllIndexs
  43.                    lblkey(El).BackColor = Color.Transparent
  44.                Next
  45.                lblkey(CInt(newIndex)).BackColor = Color.Red
  46.            Catch ex As Exception
  47.            End Try
  48.        End If
  49.    End Sub
  50.    Private Sub lblkey_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  51.         Dim indexDwn As Integer = Array.IndexOf(lblkey, sender)
  52.        lblkey(indexDwn).BackColor = Color.Red
  53.    End Sub
  54.    Private Sub lblkey_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  55.        For I As Integer = 0 To lblkey.Count - 1
  56.            lblkey(I).BackColor = Color.Transparent
  57.        Next
  58.    End Sub
  59. End Class
  60.  

lo que hay en Form_Load es para crear los Labels, configurarlos, y los eventos .

S2s



Había una errata en Mouse_Down, ya está corregida (Al hacer clic se activaba el siguiente)

Acabo de darme cuenta que el algoritmo funciona incluso aunque pongas 0 o 1 en lugar del máximo índice (N), de hecho se puede eliminar N. Ya lo he quitado.

Código
  1.  Dim newIndex As Double = N - ((N -index) - Conversion.Int(lblPoint.X / 20))

Mejor así:

Código
  1.  Dim newIndex As Double =  - ((-index) - Conversion.Int(lblPoint.X / 20))


También se podría poner así:

Código
  1.  Dim newIndex As Double = ((index * (-1)) - Conversion.Int(lblPoint.X / 20)) * (-1)
54  Programación / .NET (C#, VB.NET, ASP) / Re: Disfruta tocando el Piano con este programa en: 14 Junio 2016, 23:57 pm
Hola

Gracias por los consejos, muy buenos. La verdad es que esas cosas me hace falta saberlas, para que el código sea profesional, ya que yo he aprendido de forma autodidacta y lo pongo todo de cualquier manera aunque he mejorado. Además que el 80% de lo que se lo he aprendido aquí y con la MSDN, porque no he cogido un libro de NET en la vida. Si en su día de VB6 y algunos aún los conservo.

En el primer código cometiste una errata sin importancia, pero todo hay que mencionarlo, tienes declarado un método que se llama "ConstruyeTeclado",

 :xD
Bueno, yo quería ponerlo todo en inglés, pero eso se me pasó y encima con errata.
Ya lo he corregido.

La idea es mostrar una forma de crear sonidos sin necesidad de incrustar archivos de sonido a nuestro programa y que no fuera tampoco el típico Beep, que se escucha a través del altavoz interno.

Por cierto que curiosamente creo que de todos los sonidos no está el sonido "pulse" que creo que es así como se llama a sonido que produce  el Beep.

S2s




6. No uses el keyword Call, ¡jamás!. No necesitas hacerlo, tampoco se recomiendo hacerlo, y aparte, está mal visto hacerlo, ya que es sinónimo de un acercamiento a las costumbres de VB6.

Corregido


Creo que he corregido más o menos todo.  Gracias de nuevo.

Lo del mouse_event estoy en ello, casi está, pero me voy a dormir ::)
55  Programación / .NET (C#, VB.NET, ASP) / Re: Quitar enfoque al salir de un objeto y en MouseDown en: 14 Junio 2016, 10:01 am
Me hubiera gustado también hacerlo sin "código no manejado", realmente llevo varios días ocupado y no he tenido tiempo de intentarlo! Parece que @Eleкtro también ha estado ocupado, de seguro hubiéramos visto una respuesta de el.

En cuanto tenga un chance voy a probar!

Salu2s

Gracias

De seguro que @Eleкtro sabría hacerlo, y lo que hiciera no se si lo entendería pero mientras funcioné chapó.

He estado probando con System.Windows.Forms.MouseEventArgs y Sender, creo que por ahí van los tiros pero sin éxito.

Lo que quiero hacer no es algo que la gente demande y se encuentre buscando en google. Hay que tirar de ingenio. 

s2s
56  Programación / .NET (C#, VB.NET, ASP) / Código para reproducir notas musicales mediante midiOutShortMsg en: 14 Junio 2016, 00:12 am
Hola

Quiero compartir este programa que he desarrollado.

Se trata de un teclado musical, un piano que utiliza el parche Standard MIDI Patch Assignments del MIDI Manufacturers Association (MMA) con 128 sonidos de instrumentos diferentes.

Standard MIDI Patch Assignments


Permite tanto tocar con el ratón como con el teclado del ordenador.



Puedes descargarte el código aquí:

Musical_Keyboard.zip

*Elige el botón de la derecha, el que pone  'Descargar con el navegador'



Si lo prefieres puedes hacer simplemente un copia y pega en un nuevo proyecto 'Aplicación de Windows Form'

No necesitas crear controles, tan solo deja todo en blanco en el editor de código de Form1.vb, y pegas este código:

Código
  1. '//////////////////////////////
  2. '//    Date: 13/06/2016      //
  3. '//  Programmed by LEKIM     //
  4. '//////////////////////////////
  5.  
  6. Option Strict On
  7. Imports System.Runtime.InteropServices
  8. Imports System.Text
  9. Imports System.Security
  10.  
  11. Public Class Form1
  12.    Dim lblMuscKey(61) As Label
  13.    Dim lblInstruments(127) As Label
  14.    Dim lblOctave(5) As Label
  15.    Dim FlLayPanel As FlowLayoutPanel
  16.    Dim lblTitle As New Label
  17.    Dim ttip As New ToolTip
  18.    Dim numKeysBlack() As Integer = _
  19.        {2, 4, 7, 9, 11, 14, 16, 19, 21, 23, 26, 28, 31, _
  20.         33, 35, 38, 40, 43, 45, 47, 50, 52, 55, 57, 59}
  21.    Dim numKeysWhite() As Integer = _
  22.        {1, 3, 5, 6, 8, 10, 12, 13, 15, 17, 18, 20, 22, _
  23.         24, 25, 27, 29, 30, 32, 34, 36, 37, 39, 41, 42, _
  24.         44, 46, 48, 49, 51, 53, 54, 56, 58, 60, 61}
  25.    Dim hMidiOut As IntPtr
  26.    Dim intMsg As Integer
  27.    Dim Msg As NativeMethods.MidiMsg
  28.    Dim Octave As Byte = 1 'Octave from where begins the first key of the musical keyboard
  29.    Dim ListKeyPress As New List(Of Integer)
  30.    Dim VolumeKey As Byte = 127 'min=0; max=127
  31.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  32.        CreateMusicalKeyBoard()
  33.        CreatePanelInstruments()
  34.        CreateOctaveButtons()
  35.        With lblTitle
  36.            .Text = "Standard MIDI Patch Assignments"
  37.            .BackColor = Color.Transparent
  38.            .ForeColor = Color.WhiteSmoke
  39.            .Font = New Font("Arial", 20, FontStyle.Bold)
  40.            .TextAlign = ContentAlignment.MiddleLeft
  41.            .Size = CType(New Point(470, 40), Drawing.Size)
  42.            .Location = New Point(5, 5)
  43.        End With
  44.  
  45.        With Me
  46.            .Controls.Add(lblTitle)
  47.            .KeyPreview = True
  48.            .BackColor = System.Drawing.Color.FromArgb(40, 40, 40)
  49.            .Size = CType(New Point(835, 440), Drawing.Size)
  50.            .Text = "Demo Musical Keyboard"
  51.            .MaximizeBox = False
  52.            .FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
  53.            .StartPosition = FormStartPosition.CenterScreen
  54.            .SetBounds(CInt((Screen.PrimaryScreen.Bounds.Width - .Width) / 2),
  55.                       CInt((Screen.PrimaryScreen.Bounds.Height - .Height) / 2) - 50,
  56.                       .Width, .Height)
  57.        End With
  58.  
  59.        'Show a tooltip message
  60.        ttip.AutoPopDelay = 2000
  61.        ttip.InitialDelay = 1000
  62.        ttip.ReshowDelay = 500
  63.        For I As Integer = 1 To 5
  64.            ttip.SetToolTip(Me.lblOctave(I), "Octave")
  65.        Next
  66.  
  67.  
  68.        NativeMethods.midiOutOpen(hMidiOut, _
  69.                                  NativeMethods.MIDI_MAPPER, CType(0, IntPtr), _
  70.                                        CType(0, IntPtr), NativeMethods.CALLBACK_NULL)
  71.    End Sub
  72.    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
  73.        If ListKeyPress.Contains(e.KeyCode) = True Then Exit Sub ' Key is already pressed
  74.        If Key(e.KeyCode) = 0 Then Exit Sub
  75.        PlayMusicalNote(CByte(Key(e.KeyCode)), VolumeKey, Octave)
  76.        ListKeyPress.Add(e.KeyCode)
  77.    End Sub
  78.    Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
  79.  
  80.        OffMusicalNote(CByte(Key(e.KeyCode)), Octave)
  81.        ListKeyPress.Remove(e.KeyCode)
  82.        Try
  83.            If numKeysWhite.Contains(Msg.Note) Then
  84.                lblMuscKey(Msg.Note).BackColor = Color.White
  85.            Else
  86.                lblMuscKey(Msg.Note).BackColor = Color.Black
  87.            End If
  88.        Catch ex As Exception
  89.        End Try
  90.  
  91.    End Sub
  92.  
  93. #Region "Octave Buttons"
  94.    Sub CreateOctaveButtons()
  95.        Dim pOct As New Point(30, 265)
  96.        Dim inc As Integer = 0
  97.        For I = 1 To 5
  98.            lblOctave(I) = New Label
  99.            With lblOctave(I)
  100.                .Text = CStr(I)
  101.                .Font = New Font("Arial", 10, FontStyle.Bold)
  102.                .Size = CType(New Point(20, 20), Drawing.Size)
  103.                .BorderStyle = BorderStyle.FixedSingle
  104.                .Location = New Point(pOct.X + inc, pOct.Y)
  105.                .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
  106.                .BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
  107.                .TextAlign = ContentAlignment.MiddleCenter
  108.                AddHandler .MouseDown, AddressOf lblOctave_MouseDown
  109.                AddHandler .MouseEnter, AddressOf lblOctave_MouseEnter
  110.                AddHandler .MouseLeave, AddressOf lblOctave_MouseLeave
  111.            End With
  112.            inc = inc + 19
  113.            Me.Controls.Add(lblOctave(I))
  114.        Next
  115.  
  116.        lblOctave(1).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
  117.        lblOctave(1).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)
  118.  
  119.    End Sub
  120.    Private Sub lblOctave_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  121.        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
  122.        For I As Integer = 1 To 5
  123.            lblOctave(I).BackColor = System.Drawing.Color.FromArgb(20, 20, 20)
  124.            lblOctave(I).ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
  125.        Next
  126.        lblOctave(Index).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
  127.        lblOctave(Index).ForeColor = System.Drawing.Color.FromArgb(10, 10, 10)
  128.  
  129.        Octave = CByte(Index)
  130.    End Sub
  131.    Private Sub lblOctave_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs)
  132.        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
  133.        Cursor = Cursors.Hand
  134.    End Sub
  135.    Private Sub lblOctave_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
  136.        Dim Index As Integer = Array.IndexOf(lblOctave, sender)
  137.        Cursor = Cursors.Default
  138.    End Sub
  139. #End Region
  140.  
  141. #Region "Panel of Instruments"
  142.    ''' <summary>
  143.    ''' Create a panel of instruments
  144.    ''' </summary>
  145.    ''' <remarks></remarks>
  146.    Public Sub CreatePanelInstruments()
  147.        FlLayPanel = New FlowLayoutPanel
  148.        With FlLayPanel
  149.            .AutoScroll = True
  150.            .VerticalScroll.Visible = False
  151.            .BorderStyle = BorderStyle.FixedSingle
  152.            .Size = CType(New Point(808, 205), Drawing.Size)
  153.            .Location = New Point(5, 50)
  154.            .FlowDirection = FlowDirection.TopDown
  155.            .BackColor = System.Drawing.Color.FromArgb(10, 10, 10)
  156.        End With
  157.        Me.Controls.Add(FlLayPanel)
  158.  
  159.        For I As Integer = 0 To lblInstruments.Count - 1
  160.            lblInstruments(I) = New Label
  161.            With lblInstruments(I)
  162.                .Width = 155
  163.                .Font = New Font("Arial", 8, FontStyle.Bold)
  164.                .ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
  165.                .BorderStyle = BorderStyle.FixedSingle
  166.                .TextAlign = ContentAlignment.MiddleLeft
  167.  
  168.            End With
  169.            FlLayPanel.Controls.Add(lblInstruments(I))
  170.        Next (I)
  171.  
  172.        'Standard MIDI Patch Assignments
  173.        Dim strInstruments() As String = _
  174.            {"000 Acoustic grand piano", "001 Bright acoustic piano", "002 Electric grand piano", "003 Honky-tonk piano",
  175.             "004 Rhodes(piano)", "005 Chorused(piano)", "006 Harpsichord", "007 Clavinet", "008 Celesta",
  176.             "009 Glockenspiel", "010 Music(box)", "011 Vibraphone", "012 Marimba", "013 Xylophone", "014 Tubular(bells)",
  177.             "015 Dulcimer", "016 Hammond(organ)", "017 Percussive(organ)", "018 Rock(organ)", "019 Church(organ)",
  178.             "020 Reed(organ)", "021 Accordion", "022 Harmonica", "023 Tango(accordion)", "024 Acoustic guitar (nylon)",
  179.             "025 Acoustic(guitar(steel))", "026 Electric(guitar(jazz))", "027 Electric(guitar(clean))",
  180.             "028 Electric(guitar(muted))", "029 Overdriven(guitar)", "030 Distortion(guitar)", "031 Guitar(harmonics)",
  181.             "032 Acoustic bass", "033 Electric bass (finger)", "034 Electric bass (pick)", "035 Fretless bass",
  182.             "036 Slap bass 1", "037 Slap bass 2", "038 Synth bass 1", "039 Synth bass 2", "040 Violin",
  183.             "041 Viola", "042 Cello", "043 Contrabass", "044 Tremolo strings", "045 Pizzicato strings", "046 Orchestral harp",
  184.             "047 Timpani", "048 String ensemble 1", "049 String ensemble 2", "050 Synth.strings(1)", "051 Synth.strings(2)",
  185.             "052 Choir(Aahs)", "053 Voice(Oohs)", "054 Synth(voice)", "055 Orchestra(hit)", "056 Trumpet", "057 Trombone",
  186.             "058 Tuba", "059 Muted(trumpet)", "060 French(horn)", "061 Brass(section)", "062 Synth.brass(1)",
  187.             "063 Synth.brass(2)", "064 Soprano sax", "065 Alto sax", "066 Tenor sax", "067 Baritone sax", "068 Oboe",
  188.             "069 English horn", "070 Bassoon", "071 Clarinet", "072 Piccolo", "073 Flute", "074 Recorder",
  189.             "075 Pan flute", "076 Bottle blow", "077 Shakuhachi", "078 Whistle", "079 Ocarina", "080 Lead 1 (square)",
  190.             "081 Lead 2 (sawtooth)", "082 Lead 3 (calliope lead)", "083 Lead 4 (chiff lead)", "084 Lead 5 (charang)",
  191.             "085 Lead 6 (voice)", "086 Lead 7 (fifths)", "087 Lead 8 (brass + lead)", "088 Pad 1 (new age)",
  192.             "089 Pad 2 (warm)", "090 Pad 3 (polysynth)", "091 Pad 4 (choir)", "092 Pad 5 (bowed)", "093 Pad 6 (metallic)",
  193.             "094 Pad 7 (halo)", "095 Pad 8 (sweep)", "096 FX 1 (rain)", "097 FX 2 (soundtrack)", "098 FX 3 (crystal)",
  194.             "099 FX 4 (atmosphere)", "100 FX 5 (brightness)", "101 FX 6 (goblins)", "102 FX 7 (echoes)", "103 FX 8 (sci-fi)",
  195.             "104 Sitar", "105 Banjo", "106 Shamisen", "107 Koto", "108 Kalimba", "119 Bagpipe", "110 Fiddle", "111 Shanai2",
  196.             "112 Tinkle Bell", "113 Agogo", "114 Steel Drums", "115 Woodblock", "116 Taiko Drum", "117 Melodic Tom",
  197.             "118 Synth Drum2", "119 Reverse Cymbal", "120 Guitar fret noise", "121 Breath noise", "122 Seashore",
  198.             "123 Bird tweet", "124 Telephone ring", "125 Helicopter", "126 Applause", "127 Gunshot"}
  199.  
  200.        For I = 0 To 127
  201.            lblInstruments(I).Text = strInstruments(I)
  202.        Next
  203.        For I As Integer = 0 To lblInstruments.Count - 1
  204.            AddHandler lblInstruments(I).MouseDown, AddressOf lblInstruments_MouseDown
  205.        Next
  206.  
  207.    End Sub
  208.    Private Sub lblInstruments_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  209.        Dim Index As Integer = Array.IndexOf(lblInstruments, sender)
  210.        For I = 0 To lblInstruments.Count - 1
  211.            lblInstruments(I).BackColor = Color.Transparent
  212.            lblInstruments(I).ForeColor = System.Drawing.Color.FromArgb(120, 120, 120)
  213.  
  214.        Next
  215.        lblInstruments(Index).BackColor = System.Drawing.Color.FromArgb(150, 150, 150)
  216.        lblInstruments(Index).ForeColor = System.Drawing.Color.FromArgb(0, 0, 0)
  217.        ChangeInstrument(Index)
  218.    End Sub
  219. #End Region
  220.  
  221. #Region "Musical Keyboard"
  222.    ''' <summary>
  223.    ''' Create the keys of the musical keyboard
  224.    ''' </summary>
  225.    ''' <remarks></remarks>
  226.    Sub CreateMusicalKeyBoard()
  227.        Dim wKeyWhite As New Point(22, 80)
  228.        Dim wKeyBlack As New Point(12, 50)
  229.        Dim PosKeyWhite As New Point(30, 300)
  230.        Dim PosKeyBlack As New Point(25, 300)
  231.  
  232.        For Index As Integer = 1 To lblMuscKey.Count - 1
  233.            lblMuscKey(Index) = New Label
  234.            With lblMuscKey(Index)
  235.                .BorderStyle = BorderStyle.FixedSingle
  236.                Dim incWhiteKeyPosX As Integer
  237.                'White keys
  238.                If numKeysWhite.Contains(Index) Then
  239.                    .Size = New Size(wKeyWhite)
  240.                    .BackColor = Color.White
  241.                    .Location = _
  242.                        New Point(PosKeyWhite.X + incWhiteKeyPosX, PosKeyWhite.Y)
  243.                    incWhiteKeyPosX = incWhiteKeyPosX + 21
  244.                    .SendToBack() 'send to back
  245.                End If
  246.                'Black keys
  247.                If numKeysBlack.Contains(Index) Then
  248.                    .BackColor = Color.Black
  249.                    .Size = New Size(wKeyBlack)
  250.                    .Location = _
  251.                        New Point(PosKeyBlack.X + incWhiteKeyPosX, PosKeyBlack.Y)
  252.                End If
  253.                Me.Controls.Add(lblMuscKey(Index))
  254.                If numKeysBlack.Contains(Index) Then
  255.                    lblMuscKey(Index).BringToFront()
  256.                End If
  257.  
  258.                AddHandler .MouseDown, AddressOf lblMuscKey_MouseDown
  259.                AddHandler .MouseUp, AddressOf lblMuscKey_MouseUp
  260.                AddHandler .MouseMove, AddressOf lblMuscKey_MouseMove
  261.                AddHandler .MouseLeave, AddressOf lblMuscKey_MouseLeave
  262.            End With
  263.  
  264.        Next
  265.  
  266.  
  267.    End Sub
  268.    Private Sub lblMuscKey_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  269.        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
  270.        lblMuscKey(Index).BackColor = Color.Gray 'Change color of the key
  271.        PlayMusicalNote(CByte(Index), VolumeKey, Octave)
  272.    End Sub
  273.    Private Sub lblMuscKey_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  274.        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
  275.        If numKeysWhite.Contains(Index) Then
  276.            lblMuscKey(Index).BackColor = Color.White 'Change color of the key
  277.        Else
  278.            lblMuscKey(Index).BackColor = Color.Black 'Change color of the key
  279.        End If
  280.  
  281.        OffMusicalNote(Index, Octave)
  282.    End Sub
  283.    Private Sub lblMuscKey_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
  284.        Dim Index As Integer = Array.IndexOf(lblMuscKey, sender)
  285.        Dim mPoint As New Point(Me.PointToClient(Cursor.Position).X, Me.PointToClient(Cursor.Position).Y)
  286.        Dim X As Integer = mPoint.X
  287.        Cursor = Cursors.Hand
  288.        If X < CInt(lblMuscKey(Index).Left) Or
  289.            X > (CInt(lblMuscKey(Index).Left) + _
  290.                 CInt(lblMuscKey(Index).Width)) Then
  291.            EventoUp()
  292.            EventoDown()
  293.        End If
  294.  
  295.    End Sub
  296.    Private Sub lblMuscKey_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)
  297.        Cursor = Cursors.Default
  298.    End Sub
  299. #End Region
  300.  
  301.  
  302. #Region "Play Sounds Functions"
  303.    ''' <summary>
  304.    ''' Play a musical note
  305.    ''' </summary>
  306.    ''' <param name="Note">Value of musical note</param>  
  307.    ''' <param name="Volume">Volume musical note</param>
  308.    ''' <param name="bOct">Octave</param>
  309.    ''' <returns></returns>
  310.    Public Function PlayMusicalNote(ByVal Note As Integer, ByVal Volume As Byte, ByVal bOct As Byte) As Boolean
  311.        Note += 23 + (12 * bOct)
  312.        intMsg = CInt(Volume * Convert.ToInt32(CStr(10000), 16) _
  313. + Note * Convert.ToInt32(CStr(100), 16) + NativeMethods.KeyOn)
  314.  
  315.        Return CBool(NativeMethods.midiOutShortMsg(hMidiOut, intMsg))
  316.    End Function
  317.    ''' <summary>
  318.    ''' Off a musical note
  319.    ''' </summary>
  320.    ''' <param name="Note">Value of musical note</param>
  321.    ''' <param name="bOct">Octave</param>
  322.    ''' <returns></returns>
  323.    ''' <remarks></remarks>
  324.    Public Function OffMusicalNote(ByVal Note As Integer, ByVal bOct As Integer) As Boolean
  325.        Note += 23 + (12 * bOct)
  326.        intMsg = Note * Convert.ToInt32(CStr(100), 16) + NativeMethods.KeyOff
  327.        Return CBool(NativeMethods.midiOutShortMsg(hMidiOut, intMsg))
  328.    End Function
  329.    ''' <summary>
  330.    ''' Change the instrument
  331.    ''' </summary>
  332.    ''' <param name="instCode"></param>
  333.    ''' <returns></returns>
  334.    ''' <remarks></remarks>
  335.    Public Function ChangeInstrument(ByVal instCode As Integer) As Boolean
  336.        intMsg = instCode * Convert.ToInt32(CStr(100), 16) + NativeMethods.Instruments
  337.        Return CBool(NativeMethods.midiOutShortMsg(hMidiOut, intMsg))
  338.        Return Nothing
  339.    End Function
  340. #End Region
  341. #Region "Computer keyboard keys"
  342.    ''' <summary>
  343.    ''' Assigning Computer keyboard keys
  344.    ''' </summary>
  345.    ''' <param name="keycode"></param>
  346.    ''' <returns></returns>
  347.    ''' <remarks></remarks>
  348.    Public Function Key(ByVal keycode As Integer) As Integer
  349.        Dim BlackHalfKey() As Keys = {Keys.W, Keys.E, Keys.T, Keys.Y, Keys.U}
  350.        Dim WhiteHalfKey() As Keys = {Keys.A, Keys.S, Keys.D, Keys.F, Keys.G, Keys.H, Keys.J, Keys.K}
  351.        Dim BassKey() As Keys = {Keys.Z, Keys.X, Keys.C, Keys.V, Keys.B, Keys.N, Keys.M, Keys.Oemcomma}
  352.        Dim AltoKey() As Keys = {Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8}
  353.  
  354.        If BlackHalfKey.Contains(CType(keycode, Keys)) Or _
  355.            WhiteHalfKey.Contains(CType(keycode, Keys)) Or _
  356.            BassKey.Contains(CType(keycode, Keys)) Or _
  357.             AltoKey.Contains(CType(keycode, Keys)) Then
  358.            For I As Integer = 10 To 14
  359.                If keycode = BlackHalfKey(I - 10) Then Msg.Note = CByte(numKeysBlack(I))
  360.            Next
  361.  
  362.            For I As Integer = 14 To 21
  363.                If keycode = WhiteHalfKey(I - 14) Then Msg.Note = CByte(numKeysWhite(I))
  364.            Next
  365.  
  366.            For I As Integer = 0 To 7
  367.                If keycode = BassKey(I) Then Msg.Note = CByte(numKeysWhite(I))
  368.            Next
  369.            For I As Integer = 28 To 35
  370.                If keycode = AltoKey(I - 28) Then Msg.Note = CByte(numKeysWhite(I))
  371.            Next
  372.  
  373.            lblMuscKey(Msg.Note).BackColor = Color.Gray
  374.  
  375.            Return Msg.Note
  376.        Else
  377.            Return 0
  378.        End If
  379.  
  380.    End Function
  381. #End Region
  382. End Class
  383.  
  384. Module MouseEvents
  385.    ''' <summary>
  386.    ''' Simulate MouseDown the left mouse button
  387.    ''' </summary>
  388.    ''' <remarks></remarks>
  389.    Public Sub EventoDown()
  390.        NativeMethods.mouse_event(NativeMethods.MouseEventFlags.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
  391.    End Sub
  392.    ''' <summary>
  393.    ''' Simulate MouseUp the left mouse button
  394.    ''' </summary>
  395.    ''' <remarks></remarks>
  396.    Public Sub EventoUp()
  397.        NativeMethods.mouse_event(NativeMethods.MouseEventFlags.MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0)
  398.    End Sub
  399.  
  400. End Module
  401.  
  402. <SuppressUnmanagedCodeSecurity()>
  403. Friend NotInheritable Class NativeMethods
  404.    Inherits Attribute
  405.    Private Sub New()
  406.    End Sub
  407.  
  408. #Region "API MIDI message"
  409.    <DllImport("winmm.dll")>
  410.    Public Shared Function midiOutOpen(ByRef lphMidiOut As IntPtr,
  411.                                       ByVal uDeviceID As Integer,
  412.                                       ByVal dwCallback As IntPtr,
  413.                                       ByVal dwInstance As IntPtr,
  414.                                       ByVal dwFlags As UInteger) As UInteger
  415.    End Function
  416.    <DllImport("winmm.dll")>
  417.    Public Shared Function midiOutShortMsg(ByVal hMidiOut As IntPtr,
  418.                                           ByVal dwMsg As Integer) As UInteger
  419.    End Function
  420.  
  421.    <DllImport("winmm.dll")>
  422.    Public Shared Function midiOutClose(ByVal hMidiOut As IntPtr) As Integer
  423.    End Function
  424.  
  425.    <StructLayout(LayoutKind.Auto)> _
  426.    Public Structure MidiMsg
  427.        Dim status As Byte
  428.        Dim Note As Byte
  429.        Dim Volume As Byte
  430.        Dim Data3 As Byte
  431.    End Structure
  432.    Public Const MIDI_MAPPER As Int32 = -1
  433.    Public Const CALLBACK_NULL = &H0
  434.    Public Const KeyOn As Integer = &H90
  435.    Public Const KeyOff As Integer = &H80
  436.    Public Const Instruments As Integer = &HC0
  437. #End Region
  438.  
  439. #Region "API Mouse Events"
  440.  
  441.  
  442.    <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
  443.    Friend Shared Sub mouse_event(ByVal dwFlags As UInteger, _
  444.                                   ByVal dx As UInteger, _
  445.                                   ByVal dy As UInteger, _
  446.                                   ByVal dwData As UInteger, _
  447.                                   ByVal dwExtraInfo As Integer)
  448.    End Sub
  449.  
  450.    <Flags()> _
  451.    Public Enum MouseEventFlags As UInteger
  452.        MOUSEEVENTF_ABSOLUTE = &H8000
  453.        MOUSEEVENTF_LEFTDOWN = &H2
  454.        MOUSEEVENTF_LEFTUP = &H4
  455.        MOUSEEVENTF_MIDDLEDOWN = &H20
  456.        MOUSEEVENTF_MIDDLEUP = &H40
  457.        MOUSEEVENTF_MOVE = &H1
  458.        MOUSEEVENTF_RIGHTDOWN = &H8
  459.        MOUSEEVENTF_RIGHTUP = &H10
  460.        MOUSEEVENTF_XDOWN = &H80
  461.        MOUSEEVENTF_XUP = &H100
  462.        MOUSEEVENTF_WHEEL = &H800
  463.        MOUSEEVENTF_HWHEEL = &H1000
  464.    End Enum
  465.  
  466. #End Region
  467.  
  468.  
  469. End Class
  470.  


CÓDIGO BÁSICO PARA REPRODUCIR SONIDOS MIDI

Crea un Button, y pegas esto. Al pulsar el botón se escucha un sonido C2 (Do 2ª escala), que su valor es 47.


Código
  1.  
  2. Option Strict On
  3. Imports System.Runtime.InteropServices
  4. Imports System.Security
  5.  
  6. Public Class Form1
  7.    Dim hMidiOut As IntPtr
  8.    Dim intMsg As Integer
  9.    Dim msg As New NativeMethods.MidiMsg
  10.  
  11.    Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  12.        'Cierra los mensajes midi
  13.        NativeMethods.midiOutClose(hMidiOut)
  14.    End Sub
  15.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  16.        'Abre los mensajes midi
  17.        NativeMethods.midiOutOpen(hMidiOut, NativeMethods.MIDI_MAPPER,
  18.                         CType(0, IntPtr), CType(0, IntPtr),
  19.                         NativeMethods.CALLBACK_NULL)
  20.  
  21.        'Cambiar instrumento
  22.        Dim MyInstr As Integer = 1 'min:0 (piano) ; max:127 (Gunshot)
  23.        intMsg = MyInstr * Convert.ToInt32(CStr(100), 16) + NativeMethods.Instruments
  24.        NativeMethods.midiOutShortMsg(hMidiOut, intMsg)
  25.    End Sub
  26.  
  27.    Private Sub Button1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseDown
  28.        'Reproduce un sonido los mensajes midi
  29.        msg.status = NativeMethods.KeyOn
  30.        msg.Volume = 127
  31.        msg.Note = 47 '<---Sonido
  32.        intMsg = msg.Volume * Convert.ToInt32(CStr(10000), 16) + _
  33.            msg.Note * Convert.ToInt32(CStr(100), 16) + _
  34.            msg.status
  35.        NativeMethods.midiOutShortMsg(hMidiOut, intMsg)
  36.    End Sub
  37.  
  38.    Private Sub Button1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseUp
  39.        'Apaga el sonido al soltar el botón
  40.        '**El sonido debe ser el mismo que el que se quiere apagar
  41.        msg.status = NativeMethods.KeyOff
  42.        msg.Volume = 0
  43.        msg.Data3 = 0
  44.        msg.Note = 47 '<---Sonido
  45.        intMsg = msg.Volume * Convert.ToInt32(CStr(10000), 16) _
  46.            + msg.Note * Convert.ToInt32(CStr(100), 16) + _
  47.            msg.status
  48.        NativeMethods.midiOutShortMsg(hMidiOut, intMsg)
  49.    End Sub
  50. End Class
  51.  
  52.  
  53.  
  54. <SuppressUnmanagedCodeSecurity()>
  55. Friend NotInheritable Class NativeMethods
  56.    Inherits Attribute
  57.    Private Sub New()
  58.    End Sub
  59.  
  60. #Region "API MIDI message"
  61.    <DllImport("winmm.dll")>
  62.    Public Shared Function midiOutOpen(ByRef lphMidiOut As IntPtr,
  63.                                       ByVal uDeviceID As Integer,
  64.                                       ByVal dwCallback As IntPtr,
  65.                                       ByVal dwInstance As IntPtr,
  66.                                       ByVal dwFlags As UInteger) As UInteger
  67.    End Function
  68.    <DllImport("winmm.dll")>
  69.    Public Shared Function midiOutShortMsg(ByVal hMidiOut As IntPtr,
  70.                                           ByVal dwMsg As Integer) As UInteger
  71.    End Function
  72.  
  73.    <DllImport("winmm.dll")>
  74.    Public Shared Function midiOutClose(ByVal hMidiOut As IntPtr) As Integer
  75.    End Function
  76.  
  77.    <StructLayout(LayoutKind.Auto)> _
  78.    Public Structure MidiMsg
  79.        Dim status As Byte
  80.        Dim Note As Byte
  81.        Dim Volume As Byte
  82.        Dim Data3 As Byte
  83.    End Structure
  84.    Public Const MIDI_MAPPER As Int32 = -1
  85.    Public Const CALLBACK_NULL = &H0
  86.    Public Const KeyOn As Integer = &H90
  87.    Public Const KeyOff As Integer = &H80
  88.    Public Const Instruments As Integer = &HC0
  89. #End Region
  90.  
  91. End Class
  92.  
  93.  

Espero que disfrutéis del programa.

No soy un programador  experto así que supongo que los más avispados veréis cosas corregibles.

Me he visto obligado a usar APIs. He estado buscando la forma de no tener que usarlo y usar puro código .NET, pero no lo he conseguido. A no ser que use mi propia biblioteca MIDI de sonidos.

[DESLIZANDO EL CURSOR]
He preguntado en varios sitios incluido aquí como crear el efecto de arrastrar el dedo por las teclas de un piano usando el puntero del ratón y con puro código NET. Pero no he tenido éxito, por ahora.

Como alternativa, de nuevo me he visto obligado a usar llamada API. La razón es que cuando pulsas una tecla del piano y mantienes pulsado el botón izquierdo al pasar a otra tecla se mantiene el evento de la tecla inicial ignorando por completo el hecho de que el puntero se haya en una nueva tecla. Con la imposibilidad de usar MouseEnter, ya que el que trabaja es el evento MouseEnter de la primera tecla. Usando Mouse_Event emulo la acción de soltar el botón, aunque en realidad aun lo tenga pulsado justo al entrar en la otra tecla. De nuevo emulo el evento de pulsar y la nueva tecla captura el evento. Es fácil conseguirlo con elementos que no forma parte de una matriz, pero se complica al usar un array de controles. Por esta razón he tenido que usar Mouse_Event.

S2s




57  Programación / .NET (C#, VB.NET, ASP) / Re: Como pasar parametros a un archivo de flash en visual basic .net en: 13 Junio 2016, 12:55 pm
Hola

Esto es una idea que se me ocurre ahora y no lo he probado, eso para que conste.

Se me ocurre que puede descargar la web con el flash y luego modificar el html de la página para que cargue el flash con esos parámetros. si es posible claro.

58  Seguridad Informática / Seguridad / Re: Hackear de forma remota un ordenador sin Internet es posible en: 13 Junio 2016, 11:57 am

Estoy comprobandolo mientras escribo y no oigo nada, la verdad que oigo el ruido de cuando tecleo las teclas pero por los auriculares no se oye nada.


Ya me imagino a todo el mundo que entre aquí haciendo lo mismo.  :P

No en serio, tenía que enchufar la cadena en otro sitio para no escuchar los ruiditos tipo fax que producía el ordenador, claro que fue hace bastante tiempo el ordenador era más viejo, de esos con el disco duro ata, de los primeros que hacia unos ruiditos cuando trabajaba, y se podía oír el sonido 'fax' en los auriculares.

Lo he probado ahora con el portatil y el PC y tampoco escucho nada  :-\




59  Programación / .NET (C#, VB.NET, ASP) / Re: Calcular media Aritmética, Geométrica, Armónica. en: 12 Junio 2016, 20:46 pm
hola

para poner esto:

Código:
n ^ √

en código vb.net es así:

Código
  1. n ^ Math.Sqrt(x)


Por ejemplo esto :

25 ^ √12

Se podría así:

Código
  1. 25 ^ Math.Sqrt(12)

y devuelve esto:

Código:
69599,5195898361




Espero sirva..

Creo que está todo bien, si eso comentais y corrijo.



Código
  1. Option Strict On
  2.  
  3. Public Class Form1
  4.    Dim lstValorMedAritmetica As New List(Of Double) 'Variable para los valores de la media aritmética
  5.    Dim indice As Integer
  6.  
  7.    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  8.        Dim myFont As New Font("Arial", 10, FontStyle.Bold)
  9.        RadioButton1.Checked = True
  10.        RadioButton1.Text = "Media Aritmética"
  11.        RadioButton2.Text = "Media Armónica"
  12.        RadioButton3.Text = "Media Geométrica"
  13.        RadioButton4.Text = "Moda"
  14.        RadioButton5.Text = "Mediana "
  15.        RadioButton1.Font = myFont
  16.        RadioButton2.Font = myFont
  17.        RadioButton3.Font = myFont
  18.        RadioButton4.Font = myFont
  19.        RadioButton5.Font = myFont
  20.        Me.Text = "Medidas de centralizaciónl"
  21.        Me.MaximizeBox = False
  22.        btAgregar.Text = "<< Agregar"
  23.        btCalcMed.Text = "Calcular"
  24.        txtValue.TextAlign = HorizontalAlignment.Right
  25.  
  26.    End Sub
  27.  
  28.    Private Sub btAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btAgregar.Click
  29.        Try
  30.            'Si no hay nada en la lista borra el listbox y el resultado anterior
  31.            If lstValorMedAritmetica.Count = 0 Then
  32.                ListBox1.Items.Clear()
  33.                txtResultMedArit.Text = ""
  34.            End If
  35.            'Añade un valor a la lista
  36.            lstValorMedAritmetica.Add(CDbl(txtValue.Text))
  37.            'Añade un valor a listbox
  38.            ListBox1.Items.Add(txtValue.Text)
  39.            btCalcMed.Enabled = True
  40.        Catch ex As Exception
  41.            MessageBox.Show("Valor no válido", _
  42.                            "Atención", _
  43.                            MessageBoxButtons.OK, _
  44.                            MessageBoxIcon.Exclamation)
  45.        End Try
  46.  
  47.    End Sub
  48.  
  49.    Private Sub btCalcMed_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btCalcMed.Click
  50.        'Calcula la media aritmética
  51.        If RadioButton1.Checked = True Then
  52.            txtResultMedArit.Text =
  53.                CStr(modEstadisticFunctions.MediaAritmetica(lstValorMedAritmetica).ToString("0.00"))
  54.        End If
  55.        'Calcula la media armónica
  56.        If RadioButton2.Checked = True Then
  57.            txtResultMedArit.Text =
  58.                CStr(modEstadisticFunctions.MediaArmonica(lstValorMedAritmetica).ToString("0.00"))
  59.        End If
  60.        'Calcula Media Geométrica
  61.        If RadioButton3.Checked = True Then
  62.            txtResultMedArit.Text =
  63.                CStr(modEstadisticFunctions.MediaGeometrica(lstValorMedAritmetica).ToString("0.00"))
  64.        End If
  65.        'Calcula moda
  66.        If RadioButton4.Checked = True Then
  67.            txtResultMedArit.Text = CStr(
  68.                modEstadisticFunctions.Moda(lstValorMedAritmetica))
  69.        End If
  70.        'Calcula mediana
  71.        If RadioButton5.Checked = True Then
  72.            txtResultMedArit.Text =
  73.                modEstadisticFunctions.Mediana(lstValorMedAritmetica)
  74.        End If
  75.        lstValorMedAritmetica.Clear()
  76.        btCalcMed.Enabled = False
  77.    End Sub
  78.  
  79.  
  80.    Private Sub txtArtimetica_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtValue.Click
  81.        txtValue.SelectAll()
  82.    End Sub
  83.  
  84. End Class
  85.  
  86. Module modEstadisticFunctions
  87.  
  88.    ''' <summary>
  89.    ''' Función para calcular la media aritmética
  90.    ''' </summary>
  91.    ''' <param name="dblValue">Variable array List</param>
  92.    ''' <returns></returns>
  93.    ''' <remarks></remarks>
  94.    Public Function MediaAritmetica(ByVal dblValue As List(Of Double)) As Double
  95.        Try
  96.            Dim Valor As Double
  97.            Dim md As Double
  98.            For I As Integer = 0 To dblValue.Count - 1
  99.                Valor += +dblValue(I)
  100.            Next
  101.            md = Valor / dblValue.Count
  102.            Return md
  103.        Catch ex As Exception
  104.            MessageBox.Show("Valor no válido", _
  105.                     "Atención", _
  106.                     MessageBoxButtons.OK, _
  107.                     MessageBoxIcon.Exclamation)
  108.            Return Nothing
  109.        End Try
  110.  
  111.    End Function
  112.    ''' <summary>
  113.    ''' Función para calcular la media armónica
  114.    ''' </summary>
  115.    ''' <param name="dblValue">Variable array List</param>
  116.    ''' <returns></returns>
  117.    ''' <remarks></remarks>
  118.    Public Function MediaArmonica(ByVal dblValue As List(Of Double)) As Double
  119.        Try
  120.            Dim Valor As Double
  121.            Dim md As Double
  122.            For I As Integer = 0 To dblValue.Count - 1
  123.                Valor += +(1 / dblValue(I))
  124.            Next
  125.            md = dblValue.Count / Valor
  126.            Return md
  127.        Catch ex As Exception
  128.            MessageBox.Show("Valor no válido", _
  129.                        "Atención", _
  130.                        MessageBoxButtons.OK, _
  131.                        MessageBoxIcon.Exclamation)
  132.            Return Nothing
  133.        End Try
  134.  
  135.    End Function
  136.    ''' <summary>
  137.    ''' Función para calcular la media geométrica
  138.    ''' </summary>
  139.    ''' <param name="dblValue">Variable array List</param>
  140.    ''' <returns></returns>
  141.    ''' <remarks></remarks>
  142.    Public Function MediaGeometrica(ByVal dblValue As List(Of Double)) As Double
  143.        Try
  144.            Dim Valor As Double = 1
  145.            Dim md As Double
  146.            For I As Integer = 0 To dblValue.Count - 1
  147.                Valor = Valor * dblValue(I)
  148.            Next
  149.            md = Valor ^ (1 / dblValue.Count)
  150.            Return md
  151.        Catch ex As Exception
  152.            MessageBox.Show("Valor no válido", _
  153.                               "Atención", _
  154.                               MessageBoxButtons.OK, _
  155.                               MessageBoxIcon.Exclamation)
  156.            Return Nothing
  157.        End Try
  158.  
  159.  
  160.    End Function
  161.    ''' <summary>
  162.    ''' Función para calcular la Moda
  163.    ''' </summary>
  164.    ''' <param name="dblValue">Variable array List</param>
  165.    ''' <returns></returns>
  166.    ''' <remarks></remarks>
  167.    Public Function Moda(ByVal dblValue As List(Of Double)) As Double
  168.        Try
  169.            Return dblValue.Max() 'Obtiene el número mayor
  170.        Catch ex As Exception
  171.            MessageBox.Show("Valor no válido", _
  172.                      "Atención", _
  173.                      MessageBoxButtons.OK, _
  174.                      MessageBoxIcon.Exclamation)
  175.            Return Nothing
  176.        End Try
  177.    End Function
  178.    ''' <summary>
  179.    ''' Función para calcular la Mediana
  180.    ''' </summary>
  181.    ''' <param name="dblValue">Variable array List</param>
  182.    ''' <returns></returns>
  183.    ''' <remarks></remarks>
  184.    Public Function Mediana(ByVal dblValue As List(Of Double)) As String
  185.        Try
  186.            Dim par As Double
  187.            Dim Madn As String = Nothing
  188.           dblValue.Sort()
  189.            If (dblValue.Count / 2) = CInt(dblValue.Count / 2) Then
  190.                par = CDbl(True)
  191.            Else
  192.                par = CDbl(False)
  193.            End If
  194.            Select Case par
  195.                Case CDbl(True) : Madn = String.Format("{0}-{1}",
  196.                    CStr(dblValue(CInt((dblValue.Count / 2) - 1))),
  197.                    CStr(dblValue(CInt(dblValue.Count / 2))))
  198.                Case CDbl(False) : Madn = String.Format("{0}",
  199.                    CStr(dblValue(CInt(Conversion.Int(dblValue.Count / 2)))))
  200.  
  201.            End Select
  202.            Return Madn
  203.        Catch ex As Exception
  204.            MessageBox.Show("Valor no válido", _
  205.                           "Atención", _
  206.                           MessageBoxButtons.OK, _
  207.                           MessageBoxIcon.Exclamation)
  208.            Return Nothing
  209.        End Try
  210.  
  211.    End Function
  212. End Module



Faltaría la media aritmética ponderada, pero no la he puesto porque requiere hacerlo aparte y añadir más código. Ya que se necesitan dos datos, los valores y los coeficientes de importancia.


Error corregido

Había un error en el cálculo de la mediana. Se me olvidó ordenar la lista de valores.

He añadido
Código
  1.   dblValue.Sort()

Mis disculpas :-\

S2s
60  Seguridad Informática / Seguridad / Re: Hackear de forma remota un ordenador sin Internet es posible en: 12 Junio 2016, 20:34 pm
La idea es escuchar el proceso del ordenador a través de la red eléctrica. Hay que conectar cualquier aparato de música (una cadena, un radiocasete) con salida de auriculares, en el mismo enchufe en el que está conectado el ordenador usando un ladrón múltiple o regleta ladrón:




Entonces pones el ordenador a trabajar en algo, y subes el volumen del aparato musical a tope (sin música, repito) y puede que escuches el proceso de trabajo del ordenador que se transmite a través de la red eléctrica.



Páginas: 1 2 3 4 5 [6] 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ... 32
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines