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

 

 


Tema destacado: Recopilación Tutoriales y Manuales Hacking, Seguridad, Privacidad, Hardware, etc


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Asignar valores de una variable en una clase a un componente en un form !
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Asignar valores de una variable en una clase a un componente en un form !  (Leído 3,311 veces)
TrashAmbishion


Desconectado Desconectado

Mensajes: 755


Ver Perfil
Asignar valores de una variable en una clase a un componente en un form !
« en: 22 Enero 2020, 04:48 am »

Hola,

Tengo un codigo que me detecta las coordenadas del mouse y cuando presiono sus botones esto funciona de maravilla, todo esto en una clase.

Pero quiero tomar los valores de las coordenadas y mostrarlos en labels al hacerlo me da un  Callbackoncollecteddelegate

No logro captar bien porque sucede pero creo que es por como estoy haciendo el  llamado

Form1.label1.text = coordenadas.x

Form1.label2.text = coordenadas.y

Se que el error se produce por esto pues cuando retiro estas lineas funciona perfectamente.

Se me ocurrio crear unas variables globales en la clase y con un timer en el form cada 100ms mostrarlo pero siempre hay perdida.

Alguna forma de hacerlo sin perdidas de coordenadas.

Saludos


En línea

Hadess_inf
Desesperado
Colaborador
***
Desconectado Desconectado

Mensajes: 2.048


Nueva Vida


Ver Perfil WWW
Re: Asignar valores de una variable en una clase a un componente en un form !
« Respuesta #1 en: 22 Enero 2020, 15:48 pm »

¿ Puedes publicar parte de tu código para poder ayudarte mejor ?

Saludos.


En línea

RoyMata

Desconectado Desconectado

Mensajes: 3


Ver Perfil
Re: Asignar valores de una variable en una clase a un componente en un form !
« Respuesta #2 en: 22 Enero 2020, 17:33 pm »

No necesitas variables globales o publicas ni tampoco un timer, ni un metodo en una clase externa. Simplemente utiliza el evento MouseMove dentro del mismo Form:
Código:
private void Form1_MouseMouse (Object sender, MouseEventArgs e)
{
     this.label1.Text = e.X;
     this.label1.Refresh();
     this.label2.Text = e.Y;
     this.label2.Refresh();
}
En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 755


Ver Perfil
Re: Asignar valores de una variable en una clase a un componente en un form !
« Respuesta #3 en: 23 Enero 2020, 06:58 am »

No necesitas variables globales o publicas ni tampoco un timer, ni un metodo en una clase externa. Simplemente utiliza el evento MouseMove dentro del mismo Form:
Código:
private void Form1_MouseMouse (Object sender, MouseEventArgs e)
{
     this.label1.Text = e.X;
     this.label1.Refresh();
     this.label2.Text = e.Y;
     this.label2.Refresh();
}

Gracias por la pronta respuesta, pero el codigo que tengo es para detectar los eventos del mouse a nivel global no solo a nivel de form.
En línea

TrashAmbishion


Desconectado Desconectado

Mensajes: 755


Ver Perfil
Re: Asignar valores de una variable en una clase a un componente en un form !
« Respuesta #4 en: 23 Enero 2020, 07:08 am »

¿ Puedes publicar parte de tu código para poder ayudarte mejor ?

Saludos.

Claro pero para no repetir codigo pues lo estaria repitiendo en otro post que ya tengo aqui te pongo a funcion donde estoy trabajando...

Código
  1.  
  2. Private Function MouseProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
  3.  
  4.        If (nCode = HC_ACTION) Then
  5.            Dim uInfo As MouseHookStruct = CType(Marshal.PtrToStructure(lParam, uInfo.GetType()), MouseHookStruct)
  6.            Select Case wParam.ToInt32()
  7.                Case WM_LBUTTONDOWN
  8.                    MouseIsPress = True     ''Para verificar si el boton sigue presionado
  9.                    RaiseEvent MouseDown(Me, New MouseEventArgs(MouseButtons.Left, 1, uInfo.pt.x, uInfo.pt.y, 0))
  10.                    ' double-click hack...
  11.                    If (m_dtLastLMouseDown.AddMilliseconds(m_iDoubleClickTime).CompareTo(Now) >= 0) Then
  12.                        RaiseEvent MouseDoubleClick(Me, New MouseEventArgs(MouseButtons.Left, 2, uInfo.pt.x, uInfo.pt.y, 0))
  13.                    Else
  14.                        m_dtLastLMouseDown = Now
  15.                    End If
  16.                Case WM_RBUTTONDOWN
  17.                    RaiseEvent MouseDown(Me, New MouseEventArgs(MouseButtons.Right, 1, uInfo.pt.x, uInfo.pt.y, 0))
  18.                    ' double-click hack...
  19.                    If (m_dtLastRMouseDown.AddMilliseconds(m_iDoubleClickTime).CompareTo(Now) >= 0) Then
  20.                        RaiseEvent MouseDoubleClick(Me, New MouseEventArgs(MouseButtons.Right, 2, uInfo.pt.x, uInfo.pt.y, 0))
  21.                    Else
  22.                        m_dtLastRMouseDown = Now
  23.                    End If
  24.                Case WM_LBUTTONUP
  25.                    MouseIsPress = False     ''Para verificar si el boton sigue presionado
  26.                    RaiseEvent MouseUp(Me, New MouseEventArgs(MouseButtons.Left, 1, uInfo.pt.x, uInfo.pt.y, 0))
  27.                Case WM_RBUTTONUP
  28.                    RaiseEvent MouseUp(Me, New MouseEventArgs(MouseButtons.Right, 1, uInfo.pt.x, uInfo.pt.y, 0))
  29.                Case Else
  30.                    If (wParam <> WM_MOUSEMOVE) Then Debug.WriteLine(wParam)
  31.            End Select
  32.  
  33.            ' uInfo es una estructura y almacena las coordenadas del mouse
  34.            ' esta funcion esta en una clase y pense en mostrar los valores en par de labels de mi form
  35.            ' Form1.label1.text = uInfo.pt.x
  36.            ' Form1.label2.text = uInfo.pt.y
  37.  
  38.            ' estas lineas dan el error que ya explicaba, espero a ver sido un poco mas claro
  39.  
  40.        End If
  41.  
  42.        Return CallNextHookEx(m_iMouseHandle, nCode, wParam, lParam)
  43.  
  44.  
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Asignar valores de una variable en una clase a un componente en un form !
« Respuesta #5 en: 30 Enero 2020, 12:28 pm »

Se me ocurrio crear unas variables globales en la clase y con un timer en el form cada 100ms mostrarlo pero siempre hay perdida.

Eso es exactamente lo que deberías hacer siempre y cuando desees mantener cierto equilibrio para que tu aplicación tenga un rendimiento óptimo sin llegar a saturar la carga de mensajes de ventana y operaciones de un control. No necesitas mostrar las nuevas coordenadas del mouse cada nanosegundo (exagerando xD), con actualizaciones en intervalos de 50ms o 100ms es más que suficiente.

Ten en cuenta que al desplazar el mouse a una posición, se enviarán decenas si no cientos de mensajes en menos de 1 segundo al procedimiento de ventana, y si por cada mensaje interceptado esperas mostrarlo en un label, pues... dependiendo de si tienes varios controles más realizando otras cosas, podrías percibir una notable ralentización y/o falta de respuesta o incluso congelación del form si tu metodología es sincrónica.



Citar
CallbackOnCollectedDelegate

La carga pesada de lo que ya he opinado, y aunque no es el motivo principal del error "CallbackOnCollectedDelegate", aquí puedes leer como si que es un síntoma que puede estar derivando en dicho error:

The callbackOnCollectedDelegate managed debugging assistant (MDA) is activated if a delegate is marshaled from managed to unmanaged code as a function pointer and a callback is placed on that function pointer after the delegate has been garbage collected.
Symptoms

Access violations occur when attempting to call into managed code through function pointers that were obtained from managed delegates. These failures, while not common language runtime (CLR) bugs, may appear to be so because the access violation occurs in the CLR code.

The failure is not consistent; sometimes the call on the function pointer succeeds and sometimes it fails. The failure might occur only under heavy load or on a random number of attempts.

El motivo del error también está explicado ahí, y más sencillo de entender aquí:

Muestra el código al completo para intentar identificar que declaración es la que está provocando dicho error.



es para detectar los eventos del mouse a nivel global no solo a nivel de form.

Para ello puedes utilizar la propiedad 'System.Windows.Forms.Cursor.Position'.



Por cierto, quizás esto te interese por lo del NoRecoil:
https://foro.elhacker.net/net/libreria_de_snippets_para_vbnet_compartan_aqui_sus_snippets-t378770.0.html;msg1875345#msg1875345



aqui te pongo a funcion donde estoy trabajando...

1. No estás mostrando la definición de la estructura MouseHookStruct, la cual podría contener errores de portabilidad en sus tipos. Te muestro como ya la defino:

MouseLowLevelHookStruct.vb
Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Contains information about a low-level mouse input event.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <remarks>
  7. ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms644970(v=vs.85).aspx"/>
  8. ''' </remarks>
  9. ''' ----------------------------------------------------------------------------------------------------
  10. <DebuggerStepThrough>
  11. <StructLayout(LayoutKind.Sequential)>
  12. Public Structure MouseLowLevelHookStruct ' MSLLHOOKSTRUCT
  13.  
  14. #Region " Fields "
  15.  
  16.    ''' <summary>
  17.    ''' The x- and y-coordinates of the cursor, in screen coordinates.
  18.    ''' </summary>
  19.    Public Point As NativePoint
  20.  
  21.    ''' <summary>
  22.    ''' If the message is <see cref="WindowMessages.WM_MouseWheel"/>,
  23.    ''' the high-order word of this member is the wheel delta.
  24.    ''' <para></para>
  25.    ''' ( The low-order word is reserved. )
  26.    ''' <para></para>
  27.    ''' A positive value indicates that the wheel was rotated forward, away from the user;
  28.    ''' a negative value indicates that the wheel was rotated backward, toward the user.
  29.    ''' <para></para>
  30.    ''' One wheel click is defined as <c>WHEEL_DELTA</c>, which is <c>120</c>.
  31.    ''' <para></para>
  32.    ''' <para></para>
  33.    ''' <para></para>
  34.    ''' If the message is <see cref="WindowMessages.WM_XButtonDown"/>, <see cref="WindowMessages.WM_XButtonUp"/>,
  35.    ''' <see cref="WindowMessages.WM_XButtonDblClk"/>, <see cref="WindowMessages.WM_NcXButtonDown"/>,
  36.    ''' <see cref="WindowMessages.WM_NcXButtonUp"/>, or <see cref="WindowMessages.WM_NcXButtonDblClk"/>,
  37.    ''' the high-order word specifies which X button was pressed or released,
  38.    ''' and the low-order word is reserved.
  39.    ''' <para></para>
  40.    ''' This value can be one or more of the following values. Otherwise, mouseData is not used.
  41.    ''' </summary>
  42.    Public MouseData As Integer
  43.  
  44.    ''' <summary>
  45.    ''' The extended-key flag, event-injected flags, context code, and transition-state flag.
  46.    ''' <para></para>
  47.    ''' This member is specified as follows. An application can use the following values to test the mouse flags.
  48.    ''' <para></para>
  49.    ''' Testing <c>LLKHF_INJECTED</c> (bit 4) will tell you whether the event was injected.
  50.    ''' If it was, then testing <c>LLKHF_LOWER_IL_INJECTED</c> (bit 1) will tell you whether or not the
  51.    ''' event was injected from a process running at lower integrity level.
  52.    ''' </summary>
  53.    Public Flags As MouseLowLevelHookStructFlags
  54.  
  55.    ''' <summary>
  56.    ''' The time stamp for this message, equivalent to what <c>GetMessageTime</c> would return for this message.
  57.    ''' </summary>
  58.    Public Time As UInteger
  59.  
  60.    ''' <summary>
  61.    ''' Additional information associated with the message.
  62.    ''' </summary>
  63.    <SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible", Justification:="Visible for API users")>
  64.    Public ExtraInfo As UIntPtr
  65.  
  66. #End Region
  67.  
  68. End Structure

NativePoint.vb
Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' Defines the x- and y- coordinates of a point.
  4. ''' </summary>
  5. ''' ----------------------------------------------------------------------------------------------------
  6. ''' <remarks>
  7. ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx"/>
  8. ''' </remarks>
  9. ''' ----------------------------------------------------------------------------------------------------
  10. <DebuggerStepThrough>
  11. <StructLayout(LayoutKind.Sequential)>
  12. Public Structure NativePoint
  13.  
  14. #Region " Fields "
  15.  
  16.    ''' ----------------------------------------------------------------------------------------------------
  17.    ''' <summary>
  18.    ''' The X-coordinate of the point.
  19.    ''' </summary>
  20.    ''' ----------------------------------------------------------------------------------------------------
  21.    Public X As Integer
  22.  
  23.    ''' ----------------------------------------------------------------------------------------------------
  24.    ''' <summary>
  25.    ''' The Y-coordinate of the point.
  26.    ''' </summary>
  27.    ''' ----------------------------------------------------------------------------------------------------
  28.    Public Y As Integer
  29.  
  30. #End Region
  31.  
  32. #Region " Constructors "
  33.  
  34.    ''' ----------------------------------------------------------------------------------------------------
  35.    ''' <summary>
  36.    ''' Initializes a new instance of the <see cref="NativePoint"/> struct.
  37.    ''' </summary>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    ''' <param name="x">
  40.    ''' The X-coordinate of the point.
  41.    ''' </param>
  42.    '''
  43.    ''' <param name="y">
  44.    ''' The Y-coordinate of the point.
  45.    ''' </param>
  46.    ''' ----------------------------------------------------------------------------------------------------
  47.    Public Sub New(x As Integer, y As Integer)
  48.        Me.X = x
  49.        Me.Y = y
  50.    End Sub
  51.  
  52.    ''' ----------------------------------------------------------------------------------------------------
  53.    ''' <summary>
  54.    ''' Initializes a new instance of the <see cref="NativePoint"/> struct.
  55.    ''' </summary>
  56.    ''' ----------------------------------------------------------------------------------------------------
  57.    ''' <param name="pt">
  58.    ''' A <see cref="Point"/> that contains the X-coordinate and the Y-coordinate.
  59.    ''' </param>
  60.    ''' ----------------------------------------------------------------------------------------------------
  61.    Public Sub New(pt As Point)
  62.        Me.New(pt.X, pt.Y)
  63.    End Sub
  64.  
  65. #End Region
  66.  
  67. #Region " Operator Conversions "
  68.  
  69.    ''' ----------------------------------------------------------------------------------------------------
  70.    ''' <summary>
  71.    ''' Performs an implicit conversion from <see cref="NativePoint"/> to <see cref="Point"/>.
  72.    ''' </summary>
  73.    ''' ----------------------------------------------------------------------------------------------------
  74.    ''' <param name="pt">
  75.    ''' The <see cref="NativePoint"/>.
  76.    ''' </param>
  77.    ''' ----------------------------------------------------------------------------------------------------
  78.    ''' <returns>
  79.    ''' The resulting <see cref="Point"/>.
  80.    ''' </returns>
  81.    ''' ----------------------------------------------------------------------------------------------------
  82.    Public Shared Widening Operator CType(pt As NativePoint) As Point
  83.        Return New Point(pt.X, pt.Y)
  84.    End Operator
  85.  
  86.    ''' ----------------------------------------------------------------------------------------------------
  87.    ''' <summary>
  88.    ''' Performs an implicit conversion from <see cref="Point"/> to <see cref="NativePoint"/>.
  89.    ''' </summary>
  90.    ''' ----------------------------------------------------------------------------------------------------
  91.    ''' <param name="pt">
  92.    ''' The <see cref="Point"/>.
  93.    ''' </param>
  94.    ''' ----------------------------------------------------------------------------------------------------
  95.    ''' <returns>
  96.    ''' The resulting <see cref="NativePoint"/>.
  97.    ''' </returns>
  98.    ''' ----------------------------------------------------------------------------------------------------
  99.    Public Shared Widening Operator CType(pt As Point) As NativePoint
  100.        Return New NativePoint(pt.X, pt.Y)
  101.    End Operator
  102.  
  103. #End Region
  104.  
  105. End Structure

MouseLowLevelHookStructFlags.vb
Código
  1. ''' ----------------------------------------------------------------------------------------------------
  2. ''' <summary>
  3. ''' An application can use the following values to test a mouse low-level flags.
  4. ''' <para></para>
  5. ''' Flags combination for <see cref="Structures.MouseLowLevelHookStruct.Flags"/> field.
  6. ''' </summary>
  7. ''' ----------------------------------------------------------------------------------------------------
  8. ''' <remarks>
  9. ''' <see href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms644970%28v=vs.85%29.aspx"/>
  10. ''' </remarks>
  11. ''' ----------------------------------------------------------------------------------------------------
  12. <Flags>
  13. Public Enum MouseLowLevelHookStructFlags As UInteger ' MSLLHOOKSTRUCTFlags
  14.  
  15.    ''' <summary>
  16.    ''' Test the event-injected (from any process) flag.
  17.    ''' </summary>
  18.    Injected = &H1 ' LLKHF_INJECTED
  19.  
  20.    ''' <summary>
  21.    ''' Test the event-injected (from a process running at lower integrity level) flag.
  22.    ''' </summary>
  23.    LowerILInjected = &H2 ' LLKHF_LOWER_IL_INJECTED
  24.  
  25. End Enum



2. Para los "hacks" del doble click, imagino que a estas alturas te dará pereza cambiarlo, pero es innecesario utilizar un objeto de tipo Date, ni TimeSpan ni StopWatch, en su lugar basta y es más eficiente con combinar la utilización de una variable de contador (para contar las veces que se repite el mensaje de ventana de un botón del mouse), la propiedad Environment.TickCount, y comprobar el valor de la función GetDoubleClickTime de la APi de Windows.

Lamentablemente no puedo mostrarte un código completo implementando lo que acabo de decir, ya que para ello tendría que extraer mucho más código para mostrar, como ya hice arriba por ejemplo.

Saludos
« Última modificación: 30 Enero 2020, 12:35 pm por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines