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

 

 


Tema destacado: Security Series.XSS. [Cross Site Scripting]


  Mostrar Mensajes
Páginas: 1 ... 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 [564] 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 ... 1236
5631  Programación / Programación General / Re: Sintaxis REGEXP para sustituir una palabra x otra en: 19 Marzo 2015, 16:01 pm
Te pongo un breve ejemplo:

Tienes esta cadena de texto:
Código:
Hola, Mundo!

Tienes esta expresión regular:
Código:
"(.+)(\,)(\s+)(.+)(\!)"

Cada pareja de paréntesis representa un grupo, cada grupo es una especie de delimitador de captura, y a la expresión debes añadirle otra pareja de paréntesis imaginaria de esta manera: "((.+)(\,)(\s+)(.+)(\!))" que representa el primer grupo de todos (es decir la captura completa), por ende:

Grupo 0: "Hola, Mundo!"
Grupo 1: "Hola"
Grupo 2: ","
Grupo 3: " "
Grupo 4: "Mundo"
Grupo 5: "!"

Conociendo lo que hemos capturado, los grupos de los que consta la captura, el índice de los grupos, y dando por hecho que se utilice el símbolo "$" para interpretar un grupo, entonces solo debemos inercambiar los grupos en el orden deseado, por ejemplo, la unión de los grupos "$4$2$3$1$5" o también "Mundo, $1!" darían cómo resultado:
Código:
Mundo, Hola!



El programa o lenguaje que estés utilizando debe tener funcionalidades de reemplazado (o replace) cómo te ha comentado el compañero Engel Lex.

Cabe mencionar que existen diferencias de sintaxis del motor Regex puede dependiendo del lenguaje en el que se utilice, por ejemplo te puedes encontrar que los grupos se representan con un símbolo/sintaxis diferente en otro lenguaje de scripting,
además de eso, en lenguajes orientados a objetos, el manejo de los grupos se suele hacer mediante el uso de miembros (classes y propiedades), en lugar de interpretar símbolos cómo "$0".

Lee las documentación de la Wikipedia, que muy pocas fuentes superan esta información:
Regular expression - Wikipedia, the free encyclopedia
 
Por último, te muestro un ejemplo en VB.Net (en C# sería lo mismo):

Código
  1. Imports System.Text.RegularExpressions
  2.  
  3. Public NotInheritable Class Form1
  4.  
  5.    Dim input As String = "Hola, Mundo!"
  6.    Dim format As String
  7.    Dim replace As String
  8.  
  9.    Dim regEx As New Regex("(.+)(\,)(\s+)(.+)(\!)", RegexOptions.IgnoreCase)
  10.  
  11.    Private Sub Test() Handles MyBase.Shown
  12.  
  13.        Dim matches As MatchCollection = regEx.Matches(input)
  14.        Dim value1 As String = matches(0).Groups(1).Value ' "Hola"
  15.        Dim value2 As String = matches(0).Groups(2).Value ' ","
  16.        Dim value3 As String = matches(0).Groups(3).Value ' " "
  17.        Dim value4 As String = matches(0).Groups(4).Value ' "Mundo"
  18.        Dim value5 As String = matches(0).Groups(5).Value ' "!"
  19.  
  20.        format = String.Format("{0}{1}{2}{3}{4}",
  21.                               value4, value2, value3, value1, value5)
  22.  
  23.        replace = input.Replace(value1, value4).
  24.                        Replace(value3 & value4, value3 & value1)
  25.  
  26.        Debug.Print(format)
  27.        Debug.Print(replace)
  28.  
  29.    End Sub
  30.  
  31. End Class

Saludos
5632  Foros Generales / Dudas Generales / Re: ¿Que voz TTS femenina es esta? en: 19 Marzo 2015, 07:50 am
@bacanzito

Gracias por interesarte en ayudar, pero el temá ya se resolvió, porfavor intenta siempre leer la última respuesta de un tema antes de postear.

Cierro el hilo para que no vuelva a suceder :P

Saludos!
5633  Programación / .NET (C#, VB.NET, ASP) / Re: ¿Hay repercusiones al cambiar hora al sistema? en: 18 Marzo 2015, 20:21 pm
para ello importo la biblioteca kernel32.

No necesitas hacer P/Invoking a ninguna función de la API de Windows, puedes recurrir al NamesPace Microsoft.VisualBasic para modificar la fecha y hora del SO:
Código
  1. Dim d As New Date(year:=2000, month:=1, day:=1,
  2.                  hour:=0, minute:=0, second:=0)
  3.  
  4. Microsoft.VisualBasic.TimeOfDay = d
  5. Microsoft.VisualBasic.DateString = d.ToString("MM/dd/yyyy")

mi pregunta es si para el sistema operativo traerá alguna repercusión ejecutar mi aplicación digamos que cada segundo adelante 30 segundos y esté así por 3 minutos? o no representaría ningún problema.

No representa ningún problema mientras el margen sea pequeño y/o la fecha esté dentro del rango de fechas permitido.

Márgenes demasiado largos podrían surgir problemas derivados cómo:

  • Aplicaciones triales que caducan, ya que muchas aplicaciones que basan su protección en la hora interna del SO les afecta el cambio (a otras aplicaciones con algoritmos de protección más sofisticados no les afecta el cambio).

  • Alteraciones en el comportamiento de ciertas aplicaciones hasta volverse inestables y en casos extremos dejen de funcionar por completo.
    Cómo por ejemplo aplicaciones de calendarios o tareas programadas que dependan de la fecha y hora real, o una aplicación que revise actualizaciones de si misma cada 7 días, etc...

  • Seguramente otro tipo de problemas, cómo no saber en el día que estás viviendo ;).

Saludos
5634  Sistemas Operativos / Windows / Re: ¿son importantes estos programas de inicio? en: 18 Marzo 2015, 07:44 am
El nombre del primer proceso define su funcionalidad por si mismo, o al menos nos podemos hacer una idea, es una aplicación que controla/administra los eventos que son disparados por los dispositivos de Epson que tengas instalados, por lo tanto, ¿será importante?, pues al menos un poquito si que lo será.

El segundo tiene que ver con la salida de audio de Realtek, otro componente de hardware de tu equipo,
y el tercero lo mismo, de Epson.

El resto puedes deshabilitarlos sin problemas, los servicios adicionales de nVidia y todo lo relacionado con MS Office no son importantes, y mucho menos el del reproductor PowerDVD.

Saludos
5635  Foros Generales / Dudas Generales / Re: ¿Que voz TTS femenina es esta? en: 17 Marzo 2015, 07:00 am

No, no es Isabel... ¡pero sí que es Mónica! (otra voz de RealSpeak)

Un millón de gracias, por fin encuentro esa voz despues de tanto tiempo.

Sample: http://www2.freedomscientific.com/downloads/realspeak-solo-direct-voices/Audio/Monica-sample.mp3
Descarga: http://ftp://ftp.freedomscientific.com/users/hj/private/WebFiles/RSD/1.0/RSD1.0.84.101-spe-Monica-enu.exe
Otras voces: http://www2.freedomscientific.com/downloads/realspeak-solo-direct-voices/realspeak-solo-direct-downloads.asp

Un saludo!
5636  Sistemas Operativos / Windows / Re: Abrir archivo portable al ejecutar windows en: 17 Marzo 2015, 06:35 am
Para solventar ese problema solo debes descubrir el uso y los valores de las variables de entorno:
http://en.wikipedia.org/wiki/Environment_variable
(casi al final de la página verás una tabla, no leas nada más que eso xD)

Este es el código que has mostrado:
Código:
copy C:\Users\Juanito\Desktop\Juanito-2.pdf %appdata%

Este es el código que has mostrado con el uso de las variables de entorno de Windows:
Código:
Copy "%UserProfile%\Desktop\Juanito-2.pdf" "%AppData%\"

PD: Escribe en consola:
Código:
Set

Saludos
5637  Programación / Java / Re: [Duda]Es posible detectar teclas si mi aplicacion no tiene el foco en: 17 Marzo 2015, 06:19 am
Muchas gracias por el aporte. Si bien estoy viendo, eso es un código hecho en C++ y si no me equivoco tiene que ver con el uso de eventos de teclado, pero la duda viene ahora:

Lo que te ha mostrado el compañero @[ Thunder | CLS ] es la referencia de la función RegisterHotKey de la API de Windows, arriba de la página te muestra la firma de la función y abajo un ejemplo de uso en C++.

Nota: Y la función UnregisterHotKey realiza lo opuesto.


Y otra cosa ¿Como es posible hacer librerías con C y C++ para poder usarlas en Java?

Antes de que sigas leyendo esto, te aconsejo que esperes nuevas respuestas al tema para que puedas hacerlo directamente en Java, te costará mucho menos esfuerzo,
sigue leyendo lo que te propongo solamente si te interesa experimentar técnicas alternativas, aunque ya te aviso que esto resultaría mucho más complejo, si no te apetece puedes omitir toda esta parrafada que he escrito abajo :).


...

Doy por hecho que no te importaría utilizar librerías de terceros en tu proyecto de Java, así que te presento un código que desarrollé hace tiempo para administrar los atajos globales del teclado (o system-wide hotkeys), el código está escrito en VB.Net, antes de seguir explicando te muestro un ejemplo de uso en puro código .Net:

Código
  1. Public Class Form1
  2.  
  3.    ''' <summary>
  4.    ''' Define the system-wide hotkey object.
  5.    ''' </summary>
  6.    Private WithEvents hotkey As HotkeyManager
  7.  
  8.    ''' <summary>
  9.    ''' Initializes a new instance of this class.
  10.    ''' </summary>
  11.    Public Sub Test() Handles MyBase.Shown
  12.  
  13.        MyClass.InitializeComponent()
  14.  
  15.        ' Registers a new global hotkey on the system. (Alt + Ctrl + A)
  16.        hotkey = New HotkeyManager(HotkeyManager.KeyModifier.Alt Or HotkeyManager.KeyModifier.Ctrl, Keys.A)
  17.  
  18.        ' Replaces the current registered hotkey with a new one. (Alt + Escape)
  19.        hotkey = New HotkeyManager(DirectCast([Enum].Parse(GetType(HotkeyManager.KeyModifier), "Alt", True), HotkeyManager.KeyModifier),
  20.                                   DirectCast([Enum].Parse(GetType(Keys), "Escape", True), Keys))
  21.  
  22.        ' Set the tag property.
  23.        hotkey.Tag = "I'm a String tag"
  24.  
  25.    End Sub
  26.  
  27.    ''' <summary>
  28.    ''' Handles the Press event of the HotKey object.
  29.    ''' </summary>
  30.    Private Sub HotKey_Press(ByVal sender As Object, ByVal e As HotkeyManager.HotKeyEventArgs) _
  31.    Handles hotkey.Press
  32.  
  33.        Dim sb As New System.Text.StringBuilder
  34.        With sb
  35.            .AppendLine(String.Format("Key.......: {0}", e.Key.ToString))
  36.            .AppendLine(String.Format("Modifier..: {0}", e.Modifier.ToString))
  37.            .AppendLine(String.Format("Identifier: {0}", e.Id))
  38.            .AppendLine(String.Format("Press-count: {0}", e.Count))
  39.            .AppendLine(String.Format("Tag: {0}", DirectCast(sender, HotkeyManager).Tag.ToString))
  40.        End With
  41.  
  42.        MessageBox.Show(sb.ToString, String.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information)
  43.  
  44.        ' Unregister the hotkey.
  45.        Me.hotkey.Unregister()
  46.  
  47.        ' Register it again.
  48.        Me.hotkey.Register()
  49.  
  50.        ' Is Registered?
  51.        Debug.WriteLine(Me.hotkey.IsRegistered)
  52.  
  53.    End Sub
  54.  
  55. End Class


Y aquí el código fuente:

Código:
' ***********************************************************************
' Author   : Elektro
' Modified : 17-March-2015
' ***********************************************************************
' <copyright file="HotkeyManager.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Option Statements "

Option Explicit On
Option Strict On
Option Infer Off

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Runtime.InteropServices

#End Region

#Region " Global Hotkey "

''' <summary>
''' Manages a system-wide hotkey.
''' </summary>
Public NotInheritable Class HotkeyManager : Inherits NativeWindow : Implements IDisposable

#Region " P/Invoke "

    ''' <summary>
    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
    ''' This class does not suppress stack walks for unmanaged code permission.
    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
    ''' </summary>
    Private NotInheritable Class NativeMethods

        ''' <summary>
        ''' Defines a system-wide hotkey.
        ''' </summary>
        ''' <param name="hWnd">The hWND.</param>
        ''' <param name="id">The identifier of the hotkey.
        ''' If the hWnd parameter is NULL, then the hotkey is associated with the current thread rather than with a particular window.
        ''' If a hotkey already exists with the same hWnd and id parameters.</param>
        ''' <param name="fsModifiers">The keys that must be pressed in combination with the key specified by the uVirtKey parameter
        ''' in order to generate the WM_HOTKEY message.
        ''' The fsModifiers parameter can be a combination of the following values.</param>
        ''' <param name="vk">The virtual-key code of the hotkey.</param>
        ''' <returns>
        ''' <c>true</c> if the function succeeds, otherwise <c>false</c>
        ''' </returns>
        <DllImport("user32.dll", SetLastError:=True)>
        Public Shared Function RegisterHotKey(
                      ByVal hWnd As IntPtr,
                      ByVal id As Integer,
                      ByVal fsModifiers As UInteger,
                      ByVal vk As UInteger
        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
        End Function

        ''' <summary>
        ''' Unregisters a hotkey previously registered.
        ''' </summary>
        ''' <param name="hWnd">The hWND.</param>
        ''' <param name="id">The identifier of the hotkey to be unregistered.</param>
        ''' <returns>
        ''' <c>true</c> if the function succeeds, otherwise <c>false</c>
        ''' </returns>
        <DllImport("user32.dll", SetLastError:=True)>
        Public Shared Function UnregisterHotKey(
                      ByVal hWnd As IntPtr,
                      ByVal id As Integer
        ) As <MarshalAs(UnmanagedType.Bool)> Boolean
        End Function

    End Class

#End Region

#Region " Properties "

    ''' <summary>
    ''' Gets the key assigned to the hotkey.
    ''' </summary>
    ''' <value>The key assigned to the hotkey.</value>
    Public ReadOnly Property Key As Keys
        Get
            Return Me.pressEventArgs.Key
        End Get
    End Property

    ''' <summary>
    ''' Gets the key-modifier assigned to the hotkey.
    ''' </summary>
    ''' <value>The key-modifier assigned to the hotkey.</value>
    Public ReadOnly Property Modifier As KeyModifier
        Get
            Return Me.pressEventArgs.Modifier
        End Get
    End Property

    ''' <summary>
    ''' Gets the unique identifier assigned to the hotkey.
    ''' </summary>
    ''' <value>The unique identifier assigned to the hotkey.</value>
    Public ReadOnly Property ID As Integer
        Get
            Return Me.pressEventArgs.Id
        End Get
    End Property

    ''' <summary>
    ''' Gets or sets the user-defined data associated with this object.
    ''' </summary>
    ''' <value>The user-defined data associated with this object.</value>
    Public Property Tag As Object

    ''' <summary>
    ''' Gets a value that specifies how many times was pressed the hotkey.
    ''' </summary>
    ''' <value>A value that specifies how many times was pressed the hotkey.</value>
    Public ReadOnly Property Count As Integer
        Get
            Return Me.count1
        End Get
    End Property
    ''' <summary>
    ''' A value that specifies how many times was pressed the hotkey.
    ''' </summary>
    Private count1 As Integer

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Specifies the avaliable key-modifiers to assign for a hotkey.
    ''' </summary>
    <FlagsAttribute>
    Public Enum KeyModifier As Integer

        ''' <summary>
        ''' Any modifier.
        ''' </summary>
        None = &H0

        ''' <summary>
        ''' The Alt key.
        ''' </summary>
        Alt = &H1

        ''' <summary>
        ''' The Control key.
        ''' </summary>
        Ctrl = &H2

        ''' <summary>
        ''' The Shift key.
        ''' </summary>
        Shift = &H4

        ''' <summary>
        ''' The Windows key.
        ''' </summary>
        Win = &H8

    End Enum

    ''' <summary>
    ''' Specifies A Windows Message Identifier.
    ''' </summary>
    Private Enum WindowsMessages As Integer

        ''' <summary>
        ''' Posted when the user presses a hot key registered by the RegisterHotKey function.
        ''' The message is placed at the top of the message queue associated with the thread that registered the hot key.
        ''' <paramref name="WParam"/>
        ''' The identifier of the hot key that generated the message.
        ''' If the message was generated by a system-defined hot key.
        ''' <paramref name="LParam"/>
        ''' The low-order word specifies the keys that were to be pressed in
        ''' combination with the key specified by the high-order word to generate the WM_HOTKEY message.
        ''' </summary>
        WM_HOTKEY = &H312

    End Enum

#End Region

#Region " Events "

    ''' <summary>
    ''' Event that is raised when a hotkey is pressed.
    ''' </summary>
    Public Event Press As EventHandler(Of HotKeyEventArgs)

    ''' <summary>
    ''' Stores the Press Event Arguments.
    ''' </summary>
    Private ReadOnly pressEventArgs As HotKeyEventArgs

    ''' <summary>
    ''' Event arguments for the Press event.
    ''' </summary>
    Public NotInheritable Class HotKeyEventArgs : Inherits EventArgs

        ''' <summary>
        ''' Gets or sets the key assigned to the hotkey.
        ''' </summary>
        ''' <value>The key assigned to the hotkey.</value>
        Public Property Key As Keys

        ''' <summary>
        ''' Gets or sets the key-modifier assigned to the hotkey.
        ''' </summary>
        ''' <value>The key-modifier assigned to the hotkey.</value>
        Public Property Modifier As KeyModifier

        ''' <summary>
        ''' Gets or sets the unique identifier assigned to the hotkey.
        ''' </summary>
        ''' <value>The unique identifier assigned to the hotkey.</value>
        Public Property Id As Integer

        ''' <summary>
        ''' Gets or sets how many times was pressed the hotkey.
        ''' </summary>
        Public Property Count As Integer

    End Class

#End Region

#Region " Exceptions "

    ''' <summary>
    ''' Exception that is thrown when a hotkey tries to register but is already registered.
    ''' </summary>
    <Serializable>
    Private NotInheritable Class IsRegisteredException : Inherits Exception

        ''' <summary>
        ''' Initializes a new instance of the <see cref="IsRegisteredException"/> class.
        ''' </summary>
        Sub New()
            MyBase.New("Unable to register because the hotkey is already registered.")
        End Sub

    End Class

    ''' <summary>
    ''' Exception that is thrown when a hotkey tries to unregister but is not registered.
    ''' </summary>
    <Serializable>
    Private NotInheritable Class IsNotRegisteredException : Inherits Exception

        ''' <summary>
        ''' Initializes a new instance of the <see cref="IsNotRegisteredException"/> class.
        ''' </summary>
        Sub New()
            MyBase.New("Unable to unregister because the hotkey is not registered.")
        End Sub

    End Class

#End Region

#Region " Constructors "

    ''' <summary>
    ''' Creates a new system-wide hotkey.
    ''' </summary>
    ''' <param name="Modifier">
    ''' Indicates the key-modifier to assign to the hotkey.
    ''' ( Can use one or more modifiers )
    ''' </param>
    ''' <param name="Key">
    ''' Indicates the key to assign to the hotkey.
    ''' </param>
    ''' <exception cref="IsRegisteredException"></exception>
    <DebuggerStepperBoundary()>
    Public Sub New(ByVal modifier As KeyModifier,
                   ByVal key As Keys)

        MyBase.CreateHandle(New CreateParams)

        Me.pressEventArgs = New HotKeyEventArgs
        With Me.pressEventArgs
            .Id = MyBase.GetHashCode()
            .Key = key
            .Modifier = modifier
            .Count = 0
        End With

        If Not NativeMethods.RegisterHotKey(MyBase.Handle,
                                            Me.ID,
                                            CUInt(Me.Modifier),
                                            CUInt(Me.Key)) Then

            Throw New IsRegisteredException

        End If

    End Sub

#End Region

#Region " Event-Handlers "

    ''' <summary>
    ''' Occurs when a hotkey is pressed.
    ''' </summary>
    Private Sub OnHotkeyPress() Handles Me.Press
        Me.count1 += 1
    End Sub

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Determines whether this hotkey is registered on the system.
    ''' </summary>
    ''' <returns>
    ''' <c>true</c> if this hotkey is registered; otherwise, <c>false</c>.
    ''' </returns>
    Public Function IsRegistered() As Boolean

        Me.DisposedCheck()

        ' Try to unregister the hotkey.
        Select Case NativeMethods.UnregisterHotKey(MyBase.Handle, Me.ID)

            Case False ' Unregistration failed.
                Return False ' Hotkey is not registered.

            Case Else ' Unregistration succeeds.
                Me.Register() ' Re-Register the hotkey before return.
                Return True ' Hotkey is registeres.

        End Select

    End Function

    ''' <summary>
    ''' Registers this hotkey on the system.
    ''' </summary>
    ''' <exception cref="IsRegisteredException"></exception>
    Public Sub Register()

        Me.DisposedCheck()

        If Not NativeMethods.RegisterHotKey(MyBase.Handle,
                                            Me.ID,
                                            CUInt(Me.Modifier),
                                            CUInt(Me.Key)) Then

            Throw New IsRegisteredException

        End If

    End Sub

    ''' <summary>
    ''' Unregisters this hotkey from the system.
    ''' After calling this method the hotkey turns unavaliable.
    ''' </summary>
    ''' <param name="resetCounter">If set to <c>true</c>, resets the htkey press count.</param>
    ''' <exception cref="WindowsApplication2.HotkeyManager.IsNotRegisteredException"></exception>
    Public Sub Unregister(Optional ByVal resetCounter As Boolean = False)

        Me.DisposedCheck()

        If Not NativeMethods.UnregisterHotKey(MyBase.Handle, Me.ID) Then
            Throw New IsNotRegisteredException
        End If

        If resetCounter Then
            Me.pressEventArgs.Count = 0
        End If

    End Sub

#End Region

#Region " Hidden methods "

    ''' <summary>
    ''' Assigns a handle to this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub AssignHandle(handle As IntPtr)
        MyBase.AssignHandle(handle)
    End Sub

    ''' <summary>
    ''' Creates a window and its handle with the specified creation parameters.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub CreateHandle(cp As CreateParams)
        MyBase.CreateHandle(cp)
    End Sub

    ''' <summary>
    ''' Destroys the window and its handle.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub DestroyHandle()
        MyBase.DestroyHandle()
    End Sub

    ''' <summary>
    ''' Releases the handle associated with this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub ReleaseHandle()
        MyBase.ReleaseHandle()
    End Sub

    ''' <summary>
    ''' Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function CreateObjRef(requestedType As Type) As System.Runtime.Remoting.ObjRef
        Return MyBase.CreateObjRef(requestedType)
    End Function

    ''' <summary>
    ''' Invokes the default window procedure associated with this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub DefWndProc(ByRef m As Message)
        MyBase.DefWndProc(m)
    End Sub

    ''' <summary>
    ''' Retrieves the current lifetime service object that controls the lifetime policy for this instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function GetLifeTimeService() As Object
        Return MyBase.GetLifetimeService
    End Function

    ''' <summary>
    ''' Obtains a lifetime service object to control the lifetime policy for this instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function InitializeLifeTimeService() As Object
        Return MyBase.InitializeLifetimeService
    End Function

    ''' <summary>
    ''' Serves as a hash function for a particular type.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function GetHashCode() As Integer
        Return MyBase.GetHashCode
    End Function

    ''' <summary>
    ''' Gets the System.Type of the current instance.
    ''' </summary>
    ''' <returns>The exact runtime type of the current instance.</returns>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function [GetType]() As Type
        Return MyBase.GetType
    End Function

    ''' <summary>
    ''' Determines whether the specified System.Object instances are considered equal.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function Equals(ByVal obj As Object) As Boolean
        Return MyBase.Equals(obj)
    End Function

    ''' <summary>
    ''' Returns a String that represents the current object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function ToString() As String
        Return MyBase.ToString
    End Function

    ''' <summary>
    ''' Gets the handle for this window.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Property Handle() As IntPtr

#End Region

#Region " WndProc "

    ''' <summary>
    ''' Invokes the default window procedure associated with this window to process messages.
    ''' </summary>
    ''' <param name="m">
    ''' A <see cref="T:System.Windows.Forms.Message"/> that is associated with the current windows message.
    ''' </param>
    Protected Overrides Sub WndProc(ByRef m As Message)

        Select Case m.Msg

            Case WindowsMessages.WM_HOTKEY  ' A hotkey is pressed.

                ' Update the pressed counter.
                Me.pressEventArgs.Count += 1

                ' Raise the Event
                RaiseEvent Press(sender:=Me, e:=Me.pressEventArgs)

            Case Else
                MyBase.WndProc(m)

        End Select

    End Sub

#End Region

#Region " IDisposable "

    ''' <summary>
    ''' To detect redundant calls when disposing.
    ''' </summary>
    Private isDisposed As Boolean = False

    ''' <summary>
    ''' Prevent calls to methods after disposing.
    ''' </summary>
    ''' <exception cref="System.ObjectDisposedException"></exception>
    Private Sub DisposedCheck()

        If Me.isDisposed Then
            Throw New ObjectDisposedException(Me.GetType().FullName)
        End If

    End Sub

    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' </summary>
    Public Sub Dispose() Implements IDisposable.Dispose
        Me.Dispose(isDisposing:=True)
        GC.SuppressFinalize(Me)
    End Sub

    ''' <summary>
    ''' Releases unmanaged and - optionally - managed resources.
    ''' </summary>
    ''' <param name="IsDisposing">
    ''' <c>true</c> to release both managed and unmanaged resources;
    ''' <c>false</c> to release only unmanaged resources.
    ''' </param>
    Protected Sub Dispose(ByVal isDisposing As Boolean)

        If Not Me.isDisposed Then

            If isDisposing Then
                NativeMethods.UnregisterHotKey(MyBase.Handle, Me.ID)
            End If

        End If

        Me.isDisposed = True

    End Sub

#End Region

End Class

#End Region

Bien, la idea sería que compilases el código a una librería.dll (lo puedes hacer con Visual Studio, creando un proyecto de tipo 'Class Library' y copiando el source de mi código)

Una vez tengas compilado el ensamblado .Net (librería.dll), solo tienes que utilizar alguna herramienta cómo JNA, JNI, o JavoNet para poder utilizarla desde tu proyecto Java.

Lo cierto es que yo no se nada de Java, pero si te ha gustado la idea entonces te intentaré orientar cómo pueda...

Se dice que JNA es mejor y más sencillo de implementar que JNI, así que tomemos cómo referencia JNA,
lo que debes hacer (según explican aquí) es crear una interface que servirá cómo wrapper de la librería .net, tal que así (esto es solo un ejemplo):

Código
  1. public interface NativeExample{
  2.  
  3.  public int method1(String param1);
  4.  public boolean mehthod2();
  5.  
  6. }

Y así para importar la librería .net:
Código
  1. NativeExample nativeExample = (NativeExample) Native.loadLibrary("librería", NativeExample.class);

Bien, si te fijas, la funcionalidad principal de la class desarrollada en .Net la expongo a traves de un constructor (o ctor):
Citar
Código
  1. ' Registers a new global hotkey on the system. (Alt + Ctrl + A)
  2. hotkey = New HotkeyManager(HotkeyManager.KeyModifier.Alt Or HotkeyManager.KeyModifier.Ctrl, Keys.A)

En la interface de Java debes especificar la misma parametización que utiliza el ctor de mi Class.

El método New acepta dos parámetros de tipo Integer (o Int32), el primer parámetro es un valor de esta enumeración del código fuente, que especifica un modificador de tecla:
Citar
Código
  1. ''' <summary>
  2. ''' Specifies the avaliable key-modifiers to assign for a hotkey.
  3. ''' </summary>
  4. <FlagsAttribute>
  5. Public Enum KeyModifier As Integer
  6.  
  7.    ''' <summary>
  8.    ''' Any modifier.
  9.    ''' </summary>
  10.    None = &H0
  11.  
  12.    ''' <summary>
  13.    ''' The Alt key.
  14.    ''' </summary>
  15.    Alt = &H1
  16.  
  17.    ''' <summary>
  18.    ''' The Control key.
  19.    ''' </summary>
  20.    Ctrl = &H2
  21.  
  22.    ''' <summary>
  23.    ''' The Shift key.
  24.    ''' </summary>
  25.    Shift = &H4
  26.  
  27.    ''' <summary>
  28.    ''' The Windows key.
  29.    ''' </summary>
  30.    Win = &H8
  31.  
  32. End Enum

Nota: Puedes combinar los valores de la enumeración, por ejemplo 4+2 = Shift+Control

El segundo parámetro sería un valor de la enumeración System.Windows.Forms.Keys de la librería de clases de .Net Framework ( documentación: http://msdn.microsoft.com/de-de/library/system.windows.forms.keys%28v=vs.110%29.aspx ), con este pequeño código en VB.Net sacamos los valores Int32:

Código
  1. For Each value As Integer In [Enum].GetValues(GetType(Keys))
  2.    Debug.WriteLine(String.Format("key: {0}", [Enum].GetName(GetType(Keys), value)))
  3.    Debug.WriteLine(String.Format("val: {0}", value))
  4.    Debug.WriteLine(String.Empty)
  5. Next value

Output:
http://pastebin.com/UyTEVAQv

Con esa implementación ya habrías conseguido registrar el Hotkey desde esta libreria .Net, pero aun faltaría lo más importante, asociar el hotkey a una acción determinada.

En mi Class expongo el evento HotkeyManager.Press que se dispara al interceptar el mensaje de ventana WM_HOTKEY (documentación: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646279%28v=vs.85%29.aspx) y se puede handlear a traves de la instancia del objeto, como viste en este ejemplo:

Citar
Código
  1.    ''' <summary>
  2.    ''' Handles the Press event of the HotKeyManager instance.
  3.    ''' </summary>
  4.    Private Sub HotKey_Press(ByVal sender As Object, ByVal e As HotkeyManager.HotKeyEventArgs) _
  5.    Handles hotkey.Press
  6.  
  7.    End Sub

Las instrucciones del interior de ese bloque de código se procesarían cuando se presione el hotkey que haya sido registrado en el sistema,
y hasta aquí es donde puedo intentar orientarte, por que no tengo ni idea de cómo exponer eventos definidos en una clase de .Net a traves de Java (ni la firma del evento), deberías preguntar y/o documentarte por ti mismo.

Un saludo!
5638  Foros Generales / Foro Libre / Re: EL VERDADERO FIN DEL MUNDO, Descubren 300 escapes masivos de metano en el Ártico en: 17 Marzo 2015, 02:38 am
Esto es MUUUY hipócrita. Hablas de no creer a la tele y demás, pero tú eres el primero en defender a los conspiradores, como el JL Camacho (¿era ese el nombre?) ese, que hablaba de reptiles y no sé qué mierdas más.

Sin acritud.

Yo no defiendo a los consparanoicos, defiendo a ALGUNAS de sus hipótesis y/o teorías las cuales para mi tienen un argumento mucho más sostenible que lo que pueda salir por la boca de un político o de un presidente, pues tengo la capacidad mental cómo para estar abierto a la ÍNFIMA posibilidad de que se esté engañando a la sociedad en muchos sentidos, en muchas cosas, y muchas de ellas serían demasiado importantes como para obviarlas.

Que un tio hable sobre gilipolleces cómo una Tierra hueca (por ejemplo, yo lo considero una tontería) no significa que yo crea en todas las gilipolleces que esa persona va diciendo, y además, ¿tú te libras de haber hablado sobre tonterías en alguna que otra ocasión a lo largo de tu vida?, ¿nunca has tenido una idea que hayas querido difundir y luego te has equivocado?, revisa a ver quien es el hipócrita, porque amigo, todos somos Humanos.

PD: Me gustaría aclarar que no ignoré tu comentario, simplemente no me di cuenta hasta ahora, lo siento.

Un saludo!
5639  Programación / Programación General / Re: Interceptar aplicacion en el momento en el que empieza en: 17 Marzo 2015, 02:00 am
me gustaria que mi programa este a la espera hasta que un proceso determinado es llamado, una vez detectado poder modificar los argumentos que se le dan, si es que se le da alguno

¿En que lenguaje de programación lo piensas llevar a cabo?, no somos adivinos...

La tarea que pides sería extremadamente fácil de llevar a cabo con los métodos y/o componentes del lenguaje en cuestión si no fuese por que además de interceptar la llamada quieres modificar los argumentos, y eso implica técnicas de hooking, o mejor dicho API Hooking, debes hookear la pre-llamada de la función "CreateProcess" de la librería "Kernel32.dll" de la API de Windows,
en la pre-llamada a la función debes traducir/interpretar los parámetros enviados por esta función y modificarlos, donde cómo se explica la documentación oficial de la MSDN, el parámetro 'lpCommandLine' (de tipo String) contiene los argumentos commandline:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx
Nota: El primer argumento (o argumento 0) siempre debe ser la ruta del proceso.

( Quizás debas hookear también la función 'ShellExecute' de la librería 'shell32.dll' para controlar la ejecución de un proceso en ciertas circunstancias )

Existen librerías para facilitar el enrutamiento de las funciones de la API de Windows, cómo por ejemplo Microsoft Detours para C/C++, y EasyHook o Nektra Deviare para C#/VB.Net;
pero si piensas llevar a cabo la tarea sin ayuda de una librería de terceros entonces te advierto que se convertirá en una tarea horriblemente laboriosa y tediosa, y, por ejemplo en lo referente a la programación .Net requerirás un nivel medio-avanzado de conocimientos sobre el P/Invoking y el hooking, cómo Delegados, Callbacks, Marshalling, e indiferentemente del lenguaje que sea tampoco etsaría demás saber utilizar técnicas de programación asíncrónicas.

A continuación te muestro un ejempo que he desarrollado en Vb.Net utilizando la librería Deviare,
el siguiente código es un hook que se adjunta a las instancias activas del proceso "explorer.exe" y a sus procesos hijos para interceptar las llamadas a la función "CreateProcess" realizadas desde dichos procesos, si el nombre del proceso es "Notepad.exe" entonces modifico los argumentos del notepad para indicarle que cargue un archivo de texto ("C:\File.txt").

Nota: No es necesario interceptar la post-llamada de la función, pero deberías hacerlo para comprobar si hubo un error evaluando el valor de retorno de la función 'GetLastError' de la librería 'kernel32.dll" (si lo piensas hacer desde .Net entonces debes comprobar el valor de la función GetLastWin32Error de la Class 'Marshal')

Nota 2: El código de abajo es solo un ejemplo, el hook no es persistente, es decir, si reinicias el proceso Explorer.exe dejará de funcionar.

Código
  1. ' Nektra Deviare: "CreateProcess" hook example, By Elektro.
  2.  
  3. Imports Nektra.Deviare2
  4. Imports System.IO
  5.  
  6. Public NotInheritable Class Form1
  7.  
  8.    Public WithEvents SpyMgr As NktSpyMgr
  9.    Public Hook As NktHook
  10.  
  11.    ReadOnly processesToAttach As IEnumerable(Of Process) =
  12.        Process.GetProcessesByName("explorer") '.Concat(Process.GetProcessesByName("cmd"))
  13.  
  14.    ReadOnly processToIntercept As String = "notepad.exe"
  15.    ReadOnly processArgs As String = "C:\File.txt" ' Notepad will try to load that filepath.
  16.  
  17.    ' "CreateProcess" API reference:
  18.    ' http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx
  19.    Dim libName As String = "kernel32.dll"
  20.    Dim funcName As String = "CreateProcessW" ' Unicode
  21.  
  22.    Dim hookFlags As eNktHookFlags = eNktHookFlags.flgOnlyPreCall Or
  23.                                     eNktHookFlags.flgAutoHookChildProcess
  24.  
  25.    Private Sub Test() Handles MyBase.Load
  26.  
  27.        Me.SpyMgr = New NktSpyMgr()
  28.        Me.SpyMgr.Initialize()
  29.  
  30.        Me.Hook = SpyMgr.CreateHook(String.Format("{0}!{1}", libName, funcName), hookFlags)
  31.  
  32.        Me.Hook.Hook(sync:=True)
  33.  
  34.        For Each proc As Process In processesToAttach
  35.            Me.Hook.Attach(procOrId:=proc.Id, sync:=True)
  36.        Next proc
  37.  
  38.    End Sub
  39.  
  40.    <MTAThread>
  41.    Private Sub OnCreateProcess_Called(ByVal hook As NktHook,
  42.                                       ByVal proc As NktProcess,
  43.                                       ByVal callInfo As NktHookCallInfo) Handles SpyMgr.OnFunctionCalled
  44.  
  45.        Dim lpApplicationNameParam As NktParam = DirectCast(callInfo.Params(0), NktParam)
  46.        Dim lpCommandLineParam As NktParam = DirectCast(callInfo.Params(1), NktParam)
  47.  
  48.        If Path.GetFileName(lpApplicationNameParam.Value.ToString).Equals(processToIntercept, StringComparison.OrdinalIgnoreCase) Then
  49.  
  50.            lpCommandLineParam.Value = String.Format("""{0}"" ""{1}""", lpApplicationNameParam.Value.ToString, Me.processArgs)
  51.  
  52.        End If
  53.  
  54.    End Sub
  55.  
  56. End Class

Y, si lo que quieres es evitar que un proceso invocado mediante la función "CreateProcess" se inicie, entonces debes modificar el valor de retorno (result) de la función y despues saltar la llamada, con Deviare puedes hacerlo así:
Código
  1.    Private Sub OnCreateProcess_Called(ByVal hook As NktHook,
  2.                                       ByVal proc As NktProcess,
  3.                                       ByVal callInfo As NktHookCallInfo) Handles SpyMgr.OnFunctionCalled
  4.  
  5.        With callInfo
  6.  
  7.            If .IsPreCall Then ' Skip precall. Avoid process creation.
  8.                .Result.Value = 1
  9.                .SkipCall()
  10.            End If
  11.  
  12.        End With
  13.  
  14.    End Sub

Nota: Cada función de la API de Windows tiene sus valores de retorno y debes documentarte primero para saber cómo va a afectar al SO el valor de retorno que utilices.

Saludos.
5640  Programación / Programación General / MOVIDO: Aprendiendo PYTHON desde cero. L29. en: 16 Marzo 2015, 20:52 pm
El tema ha sido movido a Scripting.

http://foro.elhacker.net/index.php?topic=431859.0
Páginas: 1 ... 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 [564] 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines