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

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Ayuda con funcion de "click" en raton
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Ayuda con funcion de "click" en raton  (Leído 1,931 veces)
j0lama

Desconectado Desconectado

Mensajes: 24



Ver Perfil
Ayuda con funcion de "click" en raton
« en: 29 Julio 2015, 12:25 pm »

Muy buenas, a ver si me podríais echar una mano con una función que llevo tiempo intentando buscar. Quiero que cuando con el ratón haga click izquierdo se ejecute algo, sin necesidad de que el click sea en un botón sino que sea en cualquier parte incluso en otra aplicación. Algo así como:

Código
  1. if (Mouse.DoClick())
  2.   {
  3.      //Funcion que yo quiera
  4.   }

Muchas gracias


« Última modificación: 29 Julio 2015, 13:54 pm por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.813



Ver Perfil
Re: Ayuda con funcion de "click" en raton
« Respuesta #1 en: 29 Julio 2015, 14:22 pm »

j0lama, deber utilizar las etiquetas para insertar código, lee mi firma y las reglas del foro de programación.



Es bastante más complicado que el pseudo-código que has mostrado de ejemplo.

Debes crear un hook de bajo nivel o bien puedes registrar el dispositivo del mouse mediante el modelo RAWINPUT.

Ejemplo de uso:
Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. public sealed class Form1 : Form
  8. {
  9.  
  10. private MouseHook withEventsField_mouseEvents = new MouseHook(Install: false);
  11. private MouseHook mouseEvents {
  12. get { return withEventsField_mouseEvents; }
  13. set {
  14. if (withEventsField_mouseEvents != null) {
  15. withEventsField_mouseEvents.MouseLeftDown -= MouseEvents_MouseLeftDown;
  16. }
  17. withEventsField_mouseEvents = value;
  18. if (withEventsField_mouseEvents != null) {
  19. withEventsField_mouseEvents.MouseLeftDown += MouseEvents_MouseLeftDown;
  20. }
  21. }
  22.  
  23. }
  24.  
  25. private void Form1_Load(object sender, EventArgs e)
  26. {
  27. // Install Mouse Hook on the System.
  28. this.mouseEvents.Install();
  29.  
  30. // Start processing mouse events.
  31. this.mouseEvents.Enable();
  32.  
  33. }
  34.  
  35.  
  36. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  37. {
  38. // Stop processing mouse events.
  39. this.mouseEvents.Disable();
  40.  
  41. // Uninstall the mouse hook from system.
  42. this.mouseEvents.Uninstall();
  43.  
  44. }
  45.  
  46.  
  47. private void MouseEvents_MouseLeftDown(object sender)
  48. {
  49. Trace.WriteLine(string.Format("Mouse Left Down"));
  50.  
  51. }
  52. public Form1()
  53. {
  54. FormClosing += Form1_FormClosing;
  55. Load += Form1_Load;
  56. }
  57.  
  58. }
  59.  
  60. //=======================================================
  61. //Service provided by Telerik (www.telerik.com)
  62. //Conversion powered by NRefactory.
  63. //Twitter: @telerik
  64. //Facebook: facebook.com/telerik
  65. //=======================================================
  66.  

Código fuente destripado para cumplir la función que mencionas, y convertido a C# (puede no haberse convertido correctamente):
Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. #region " Instructions "
  8.  
  9. // Go to page:
  10. // Project > Properties > Debug
  11. //
  12. // Then uncheck the option:
  13. // "Enable the Visual Studio Hosting Process"
  14.  
  15. #endregion
  16.  
  17. #region " Imports "
  18.  
  19. using System.Reflection;
  20. using System.Runtime.InteropServices;
  21.  
  22. #endregion
  23.  
  24. #region " MouseHook "
  25.  
  26. /// <summary>
  27. /// A low level mouse hook that processes mouse input events.
  28. /// </summary>
  29. internal sealed class MouseHook : IDisposable
  30. {
  31.  
  32. #region " P/Invoke "
  33.  
  34. protected sealed class NativeMethods
  35. {
  36.  
  37. #region " Methods "
  38.  
  39. [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  40. public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
  41.  
  42. [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  43. public static extern IntPtr SetWindowsHookEx(HookType idHook, LowLevelMouseProcDelegate lpfn, IntPtr hInstance, uint threadId);
  44.  
  45. [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
  46. public static extern bool UnhookWindowsHookEx(IntPtr idHook);
  47.  
  48. #endregion
  49.  
  50. #region " Enumerations "
  51.  
  52. public enum WindowsMessages : uint
  53. {
  54.  
  55. WMlButtonDown = 0x201u
  56.  
  57. }
  58.  
  59. public enum HookType : uint
  60. {
  61.  
  62. WHMouseLL = 14u
  63.  
  64. }
  65.  
  66. [Flags()]
  67. public enum MsllHookStructFlags : int
  68. {
  69.  
  70. LlmhfInjected = 1,
  71.  
  72. LlmhfLowerILInjected = 2
  73.  
  74. }
  75.  
  76. #endregion
  77.  
  78. #region " Delegates "
  79.  
  80. public delegate int LowLevelMouseProcDelegate(int nCode, NativeMethods.WindowsMessages wParam, IntPtr lParam);
  81.  
  82. #endregion
  83.  
  84. }
  85.  
  86. #endregion
  87.  
  88. #region " Properties "
  89.  
  90. /// <summary>
  91. /// Handle to the hook procedure.
  92. /// </summary>
  93. private IntPtr MouseHook { get; set; }
  94.  
  95. /// <summary>
  96. /// The mouse hook delegate.
  97. /// </summary>
  98. private NativeMethods.LowLevelMouseProcDelegate MouseHookDelegate { get; set; }
  99.  
  100. #endregion
  101.  
  102. #region " Events "
  103.  
  104. /// <summary>
  105. /// Occurs when the mouse left button is pressed.
  106. /// </summary>
  107. public event MouseLeftDownEventHandler MouseLeftDown;
  108. public delegate void MouseLeftDownEventHandler(object sender);
  109.  
  110. #endregion
  111.  
  112. #region " Constructors "
  113.  
  114. /// <summary>
  115. /// Initializes a new instance of the <see cref="MouseHook"/> class.
  116. /// </summary>
  117. /// <param name="Install">
  118. /// If set to <c>true</c>, the Hook starts initialized for this <see cref="MouseHook"/> instance.
  119. /// </param>
  120.  
  121. public MouseHook(bool install = false)
  122. {
  123. if (install) {
  124. this.Install();
  125. }
  126.  
  127. }
  128.  
  129. #endregion
  130.  
  131. #region " Public Methods "
  132.  
  133. /// <summary>
  134. /// Installs the Mouse Hook, then start processing messages to fire events.
  135. /// </summary>
  136.  
  137. public void Install()
  138. {
  139. if (this.IsVisualStudioHostingProcessEnabled()) {
  140. throw new Exception("Visual Studio Hosting Process should be deactivated.");
  141. return;
  142. }
  143.  
  144. this.MouseHookDelegate = new NativeMethods.LowLevelMouseProcDelegate(LowLevelMouseProc);
  145.  
  146. try {
  147. this.MouseHook = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WHMouseLL, this.MouseHookDelegate, new IntPtr(Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32), 0);
  148.  
  149. } catch (Exception ex) {
  150. throw;
  151.  
  152. }
  153.  
  154. }
  155.  
  156. /// <summary>
  157. /// Uninstalls the Mouse Hook and free all resources, then stop processing messages to fire events.
  158. /// </summary>
  159.  
  160. public void Uninstall()
  161. {
  162. this.Finalize();
  163.  
  164. }
  165.  
  166. #endregion
  167.  
  168. #region " Private Methods "
  169.  
  170. private bool IsVisualStudioHostingProcessEnabled()
  171. {
  172. return AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe", StringComparison.OrdinalIgnoreCase);
  173. }
  174.  
  175. private int LowLevelMouseProc(int nCode, NativeMethods.WindowsMessages wParam, IntPtr lParam)
  176. {
  177.  
  178.  
  179. if (nCode == 0) {
  180. switch (wParam) {
  181.  
  182. case NativeMethods.WindowsMessages.WMlButtonDown:
  183. if (MouseLeftDown != null) {
  184. MouseLeftDown(this);
  185. }
  186.  
  187.  
  188. break;
  189. default:
  190. // Do Nothing
  191. break; // TODO: might not be correct. Was : Exit Select
  192.  
  193.  
  194. break;
  195. }
  196.  
  197. return Convert.ToInt32(NativeMethods.CallNextHookEx(MouseHook, nCode, new IntPtr(wParam), lParam));
  198.  
  199. } else if (nCode < 0) {
  200. return Convert.ToInt32(NativeMethods.CallNextHookEx(MouseHook, nCode, new IntPtr(wParam), lParam));
  201.  
  202. // nCode > 0
  203. } else {
  204. return Convert.ToInt32(NativeMethods.CallNextHookEx(MouseHook, nCode, new IntPtr(wParam), lParam));
  205.  
  206. }
  207.  
  208. }
  209.  
  210. #endregion
  211.  
  212. #region "IDisposable Support"
  213.  
  214. /// <summary>
  215. /// Flag to detect redundant calls at <see cref="Dispose"/> method.
  216. /// </summary>
  217.  
  218. private bool disposedValue;
  219.  
  220. protected void Dispose(bool disposing)
  221. {
  222.  
  223. if (!this.disposedValue) {
  224. // Dispose managed state (managed objects).
  225. if (disposing) {
  226.  
  227. // Free unmanaged resources (unmanaged objects).
  228. } else {
  229. NativeMethods.UnhookWindowsHookEx(this.MouseHook);
  230.  
  231. }
  232.  
  233. }
  234.  
  235. this.disposedValue = true;
  236.  
  237. }
  238.  
  239.  
  240. protected override void Finalize()
  241. {
  242. // Do not change this code. Put cleanup code in method: Dispose(ByVal disposing As Boolean)
  243.  
  244. this.Dispose(disposing: false);
  245. base.Finalize();
  246.  
  247. }
  248.  
  249.  
  250. private void Dispose()
  251. {
  252. // Do not change this code. Put cleanup code in method: Dispose(ByVal disposing As Boolean)
  253.  
  254. this.Dispose(disposing: true);
  255. GC.SuppressFinalize(obj: this);
  256.  
  257. }
  258.  
  259. #endregion
  260.  
  261. }
  262.  
  263. #endregion
  264.  
  265. //=======================================================
  266. //Service provided by Telerik (www.telerik.com)
  267. //Conversion powered by NRefactory.
  268. //Twitter: @telerik
  269. //Facebook: facebook.com/telerik
  270. //=======================================================
  271.  

Código fuente original y documentado de pies a cabeza, en VB.Net:
http://pastebin.com/Bjr06jGR

Si quieres ver un ejemplo de como sería usando RAWINPUT, puedes hacerte una idea aquí:
[SOURCE] Algoritmo KeyLogger (RawInput) - By Elektro

Saludos.


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