Créer une classe Hook Souris ?!?

Résolu
AzevedoSt27 Messages postés 65 Date d'inscription mercredi 10 novembre 2010 Statut Membre Dernière intervention 27 mai 2012 - 25 avril 2012 à 11:07
Lutinore Messages postés 3246 Date d'inscription lundi 25 avril 2005 Statut Membre Dernière intervention 27 octobre 2012 - 10 mai 2012 à 00:48
Bonjour,

Voila je commence un projet qui consiste à dessiner n'importe ou sur l'écran en appuyant sur le scroll de ma souris ce qui créera un traçage rouge pendant que le clique est enfoncer ensuite en récuperant les données x et y de chaque pixel pour les analyser...

Mon problème est que je récupère les données x et y selement dans la zone de ma windows form et mon but serais qu'il n'ait pas de winform mais juste une application qui tourne en arriere plan avec un icone dans la barre de notif.

Voici mon code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Reconnaissance
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        //Declare the hook handle as an int.
        static int hHook = 0;

        //Declare the mouse hook constant.
        //For other hook types, you can obtain these values from Winuser.h in the Microsoft SDK.
        public const int WH_MOUSE = 7;
        private System.Windows.Forms.Button btnHook;

        //Declare MouseHookProcedure as a HookProc type.
        HookProc MouseHookProcedure;

        //Declare the wrapper managed POINT class.
        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public int x;
            public int y;
        }

        //Declare the wrapper managed MouseHookStruct class.
        [StructLayout(LayoutKind.Sequential)]
        public class MouseHookStruct
        {
            public POINT pt;
            public int hwnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }

        //This is the Import for the SetWindowsHookEx function.
        //Use this function to install a thread-specific hook.
        [DllImport("user32.dll", CharSet = CharSet.Auto,
         CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
        IntPtr hInstance, int threadId);

        //This is the Import for the UnhookWindowsHookEx function.
        //Call this function to uninstall the hook.
        [DllImport("user32.dll", CharSet = CharSet.Auto,
         CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);

        //This is the Import for the CallNextHookEx function.
        //Use this function to pass the hook information to the next hook procedure in chain.
        [DllImport("user32.dll", CharSet = CharSet.Auto,
         CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode,
        IntPtr wParam, IntPtr lParam);

        public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            //Marshall the data from the callback.
            MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

            if (nCode < 0)
            {
                return CallNextHookEx(hHook, nCode, wParam, lParam);
            }
            else
            {
                //Create a string variable that shows the current mouse coordinates.
                String strCaption "x " +
                        MyMouseHookStruct.pt.x.ToString("d") +
                            "  y = " +
                MyMouseHookStruct.pt.y.ToString("d");
                //You must get the active form because it is a static function.
                Form tempForm = Form.ActiveForm;

                //Set the caption of the form.
                tempForm.Text = strCaption;
                return CallNextHookEx(hHook, nCode, wParam, lParam);
            }
        }

        private void btnHook_Click(object sender, EventArgs e)
        {
            if (hHook == 0)
            {
                // Create an instance of HookProc.
                MouseHookProcedure = new HookProc(Form1.MouseHookProc);

                hHook = SetWindowsHookEx(WH_MOUSE,
                            MouseHookProcedure,
                            (IntPtr)0,
                            AppDomain.GetCurrentThreadId());
                //If the SetWindowsHookEx function fails.
                if (hHook == 0)
                {
                    MessageBox.Show("SetWindowsHookEx Failed");
                    return;
                }
                btnHook.Text = "UnHook Windows Hook";
            }
            else
            {
                bool ret = UnhookWindowsHookEx(hHook);
                //If the UnhookWindowsHookEx function fails.
                if (ret == false)
                {
                    MessageBox.Show("UnhookWindowsHookEx Failed");
                    return;
                }
                hHook = 0;
                btnHook.Text = "Set Windows Hook";
                this.Text = "Mouse Hook";
            } 

        }
    }
}


Si quelqu'un pourait m'aidez à touver une solution sa serais sympa

Merci

FifouX_x

4 réponses

Lutinore Messages postés 3246 Date d'inscription lundi 25 avril 2005 Statut Membre Dernière intervention 27 octobre 2012 41
25 avril 2012 à 11:52
Salut, de mémoire c'est un WH_MOUSE_LL qu'il faut installer et non un WH_MOUSE.

tu as un exemple qui date de 2006 ici :

http://www.csharpfr.com/forum/sujet-EVENEMENT-IMPORTE-OU-SUR-ECRAN_745061.aspx

le principe est toujours le même mais je ne sais pas si ça fonctionne sous win7.
3
AzevedoSt27 Messages postés 65 Date d'inscription mercredi 10 novembre 2010 Statut Membre Dernière intervention 27 mai 2012
25 avril 2012 à 12:06
Merci :)

Je t'ecris des que je teste sa ;)
0
AzevedoSt27 Messages postés 65 Date d'inscription mercredi 10 novembre 2010 Statut Membre Dernière intervention 27 mai 2012
7 mai 2012 à 09:54
Salut Lutinore,

j'ai essayer ton code qui figure sur le lien mais cela ne fonctionne pas j'ai un problème au niveau de unsafe.

Voici mon code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security;

namespace HookSouris
{
    public partial class Form1 : Form
    {

        #region Win32

        [StructLayout(LayoutKind.Sequential)]
        private struct MSLLHOOKSTRUCT
        {
            public int X;
            public int Y;
            public int Data;
            public int Flags;
            public int Time;
            public UIntPtr Extra;
        }

        [DllImport("user32.dll", SetLastError = true), SuppressUnmanagedCodeSecurity]
        private static extern IntPtr SetWindowsHookEx(int hook, HookProc callback, IntPtr module, uint threadID);

        [DllImport("user32.dll", SetLastError = true), SuppressUnmanagedCodeSecurity]
        private static extern bool UnhookWindowsHookEx(IntPtr hHook);

        [DllImport("user32.dll"), SuppressUnmanagedCodeSecurity]
        private static extern IntPtr CallNextHookEx(IntPtr hHook, int code, UIntPtr wParam, IntPtr lParam);

        private delegate IntPtr HookProc(int code, UIntPtr wParam, IntPtr lParam);

        private const int WH_MOUSE_LL = 14;
        private const int HC_ACTION = 0;

        #endregion Win32

        private IntPtr hHook = IntPtr.Zero;
        private HookProc hookProc = null;

        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            hookProc = new HookProc(LowLevelMouseProc);
            hHook = SetWindowsHookEx(WH_MOUSE_LL, hookProc, Marshal.GetHINSTANCE(this.GetType().Module), 0);

            if (hHook == IntPtr.Zero) // Le hook ne s'installe pas en mode DEBUG.
                MessageBox.Show("Impossible d'installer le hook.", "Erreur");
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);

            if (hHook != IntPtr.Zero)
            {
                if (!UnhookWindowsHookEx(hHook))
                    MessageBox.Show("Impossible de désinstaller le hook.", "Erreur");

                hHook = IntPtr.Zero;
                hookProc = null;
            }
        }

        private IntPtr LowLevelMouseProc(int code, UIntPtr wParam, IntPtr lParam)
        {
            if (code == HC_ACTION)
            {
                unsafe
                {
                    MSLLHOOKSTRUCT* p = (MSLLHOOKSTRUCT*)lParam;
                    Point screenPos = new Point(p->X, p->Y);
                    Point clientPos = this.PointToClient(screenPos);
                    this.Text = screenPos + " - " + clientPos; // Pour l'exemple.
                }
            }

            return CallNextHookEx(hHook, code, wParam, lParam);
        }


        
        private void Form1_Load(object sender, EventArgs e)
        {
            // L'icône de not_zero est celle de l'application.
            this.notifyIcon1.Icon = this.Icon;
        }

        private void btnMessage_Click(object sender, EventArgs e)
        {
            // Icône information de Windows.
            this.notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
            // Titre du message.
            this.notifyIcon1.BalloonTipTitle = "NotifyZero";
            // Corps du message.
            this.notifyIcon1.BalloonTipText = "Ceci est un message de NotifyZero";
            // On affiche le message indéfiniment.
            this.notifyIcon1.ShowBalloonTip(0);
        }

        private void btnErreur_Click(object sender, EventArgs e)
        {
            // Icône information de Windows.
            this.notifyIcon1.BalloonTipIcon = ToolTipIcon.Error;
            // Titre du message.
            this.notifyIcon1.BalloonTipTitle = "NotifyZero";
            // Corps du message.
            this.notifyIcon1.BalloonTipText = "Une erreur est survenue dans NotifyZero";
            // On affiche le message indéfiniment.
            this.notifyIcon1.ShowBalloonTip(9000);
        }

        private void quitterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Quitte le programme
            this.Close();
        }

        private void btnCacher_Click(object sender, EventArgs e)
        {
            // Cache la winform
            this.Hide();
        }
    }
}


Pourait tu m'aidez a enlver ce problème et m'aidez a afficher les cordonnée x et y sur le titre de la winform par exemple.

Merci :)
0
Lutinore Messages postés 3246 Date d'inscription lundi 25 avril 2005 Statut Membre Dernière intervention 27 octobre 2012 41
10 mai 2012 à 00:48
Pour compiler du code unsafe, il faut autoriser le code unsafe dans les options du projet (clique droit sur le projet).

il est possible aussi que le hook ne fonctionne pas en mode debug ou que ton application n'est pas les privilèges nécessaires (à tester en mode admin) car depuis, Windows a bcp évolué au niveau de la sécurité.
0
Rejoignez-nous