IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

[C#] Hook Clavier qui ne fonctionne pas


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Homme Profil pro
    Étudiant
    Inscrit en
    Novembre 2007
    Messages
    634
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Loire (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2007
    Messages : 634
    Par défaut [C#] Hook Clavier qui ne fonctionne pas
    Bonjour a tous,

    j'essay de me familiariser avec les hook, j'essay de faire un hook clavier mais rien ne se passe !

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    using System.Reflection;
    using System.Text;
    using System;
    using System.Runtime.InteropServices;
    using System.Collections.Generic;
    using System.Collections;
    using System.IO;
    using System.Threading;
    using System.Diagnostics;
    using System.Windows.Forms;
     
    namespace Hook
    {
        class HookClavier
        {
            #region Import Dll
            [DllImport("user32.dll")]
            static extern IntPtr GetForegroundWindow();
            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool UnhookWindowsHookEx(IntPtr hhk);
            [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern IntPtr GetModuleHandle(string lpModuleName);
            #endregion
            #region Variables
            private const int WH_KEYBOARD_LL = 13;
            private const int WM_KEYDOWN = 0x0100;
            private LowLevelKeyboardProc _proc = HookCallback;
            private static IntPtr _hookID = IntPtr.Zero;
            #endregion
            #region Delegates
            private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
            #endregion
            public String CurrentWindowsTitle()
            {
                IntPtr p = GetForegroundWindow();
                if (p == IntPtr.Zero)
                    return (String.Empty);
                StringBuilder d = new StringBuilder(256);
                GetWindowText(p, d, 256);
                return (Convert.ToString(d));
            }
            public static void Write()
            {
                 try
                {
                        String Filename = "test.txt";
                        StreamWriter sw = new StreamWriter(System.IO.Path.Combine("C:\\", FileName), true, Encoding.Unicode);
                        sw.WriteLine("test");
                        sw.Close();
                    }
                }
                catch (Exception)
                {
     
                }
            }
     
            private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
            {
                if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
                {
                    int vkCode = Marshal.ReadInt32(lParam);
                    Keys key = (Keys)vkCode;
                    HookClavier.Write();
                }
                return CallNextHookEx(_hookID, nCode, wParam, lParam);
            }
     
            public void Start()
            {
                if (_hookID == IntPtr.Zero)
                {
                    using (Process curProcess = Process.GetCurrentProcess())
                    using (ProcessModule curModule = curProcess.MainModule)
                    {
                        _hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(curModule.ModuleName), 0);
                    }
                }
            }
            public void Stop()
            {
                if (_hookID != IntPtr.Zero)
                    UnhookWindowsHookEx(_hookID);
            }
            public Boolean IsActivated
            {
                get
                {
                    if (_hookID != IntPtr.Zero)
                        return (true);
                    return (false);
                }
            }
        }
    }
    Mais rien ne sa passe je ne comprend pas pourquoi !
    Si quelqu'un pouvait m'aiguiller ca serait chouette.

    Merci.

    Cordialement,
    NeoKript

  2. #2
    Expert confirmé

    Homme Profil pro
    Chef de projet NTIC
    Inscrit en
    Septembre 2006
    Messages
    3 580
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Chef de projet NTIC
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Septembre 2006
    Messages : 3 580
    Par défaut
    Mon aide : sur codeproject.com tu as un exemple de hook en C# qui fonctionne à merveille et qui présente un hook clavier / souris

  3. #3
    Membre éclairé
    Homme Profil pro
    Étudiant
    Inscrit en
    Novembre 2007
    Messages
    634
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Loire (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2007
    Messages : 634
    Par défaut
    Je l'ai essaye et je n'arrive malheureusement pas a le faire fonctionner !
    Pour infos mon appli et une appli console et le hook ne doit bien évidement ne pas être bloquant !

  4. #4
    Membre éclairé
    Homme Profil pro
    Étudiant
    Inscrit en
    Novembre 2007
    Messages
    634
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Loire (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2007
    Messages : 634
    Par défaut
    Tu parle ce ce code : http://www.codeproject.com/KB/system...ystemhook.aspx ?

    Ce qui m'embête c'est de passer par une Dll, est-on obligé ?

  5. #5
    Membre éclairé
    Homme Profil pro
    Étudiant
    Inscrit en
    Novembre 2007
    Messages
    634
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Loire (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2007
    Messages : 634
    Par défaut
    Savez-vous a quoi correspond l'erreur 126 de SetWindowsHookEx ?

    Merci

  6. #6
    Membre éclairé
    Homme Profil pro
    Étudiant
    Inscrit en
    Novembre 2007
    Messages
    634
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Loire (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2007
    Messages : 634
    Par défaut
    Bonjours a tous,

    je viens d'essayer le hook explique ici : http://humann.developpez.com/hook/

    J'ai mis le tout dans une dll quand j'appelle StartKeyHook setWindowsHookEx retourne bien une valeur différentes de 0 mais apparemment on ne passe jamais dans la fonction de hook ...

    Voici le code, si vous avez une idée !

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Reflection;
    using System.Windows.Forms;
    using System.IO;
     
    namespace Hook
    {
        public class Hook
        {
            #region Import DLL
     
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            private static extern int UnhookWindowsHookEx(int idHook);
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            private static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);
            [DllImport("user32")]
            private static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);
            [DllImport("user32")]
            private static extern int GetKeyboardState(byte[] pbKeyState);
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            private static extern short GetKeyState(int vKey);
            #endregion
            #region Delegates
            private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
            #endregion
            #region Structures
            [StructLayout(LayoutKind.Sequential)]
            private class KeyboardHookStruct
            {
                public int vkCode;
                public int scanCode;
                public int flags;
                public int time;
                public int dwExtraInfo;
            }
            #endregion
            #region Constantes
            private const int WH_KEYBOARD_LL = 13;
            private const int WM_KEYDOWN = 0x100;
            private const int WM_KEYUP = 0x101;
            private const int WM_SYSKEYDOWN = 0x104;
            private const int WM_SYSKEYUP = 0x105;
            private const byte VK_SHIFT = 0x10;
            private const byte VK_CAPITAL = 0x14;
            private const byte VK_NUMLOCK = 0x90;
            #endregion
            #region Variables
            static Int32 _hook = 0;
            #endregion
            #region Hook Clavier
            public void Start()
            {
                if (_hook == 0)
                {
                    HookProc KeyboardHookProcedure = new HookProc(KeyboardHookProc);
                    _hook = SetWindowsHookEx(
                        WH_KEYBOARD_LL,
                        KeyboardHookProcedure,
                        Marshal.GetHINSTANCE(
                        Assembly.GetExecutingAssembly().GetModules()[0]),
                        0);
                }
            }
            public void Stop()
            {
                if (_hook != 0)
                {
                    UnhookWindowsHookEx(_hook);
                }
            }
     
            public Boolean Activated
            {
                get
                {
                    if (_hook == 0)
                        return (false);
                    return (true);
                }
            }
            private KeyPressEventHandler _onKeyPress;
     
            public event KeyPressEventHandler OnKeyPress
            {
                add
                {
                    _onKeyPress += value;
                }
                remove
                {
                    _onKeyPress -= value;
                }
            }
            private KeyEventHandler _onKeyUp;
     
            public event KeyEventHandler OnKeyUp
            {
                add
                {
                    _onKeyUp += value;
                }
                remove
                {
                    _onKeyUp -= value;
                }
            }
            private KeyEventHandler _onKeyDown;
     
            public event KeyEventHandler OnKeyDown
            {
                add
                {
                    _onKeyDown += value;
                }
                remove
                {
                    _onKeyDown -= value;
                }
            }
            private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
            {
                bool handled = false;
                //On verifie si tous est ok
                StreamWriter s = new StreamWriter("C:\\Coucou.txt", true);
                s.Write("test");
                if ((nCode >= 0) && (_onKeyDown != null || _onKeyUp != null || _onKeyPress != null))
                {
                    //Remplissage de la structure KeyboardHookStruct a partir d'un pointeur
                    KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
                    //KeyDown
                    if (_onKeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
                    {
                        Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                        KeyEventArgs e = new KeyEventArgs(keyData);
                        MessageBox.Show(Convert.ToString(keyData));
                        _onKeyDown(this, e);
                        handled = handled || e.Handled;
                    }
     
                    // KeyPress
                    if (_onKeyPress != null && wParam == WM_KEYDOWN)
                    {
                        // Si la touche Shift est appuyée
                        bool isShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false);
                        // Si la touche CapsLock est appuyée
                        bool isCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false);
     
                        byte[] keyState = new byte[256];
                        GetKeyboardState(keyState);
                        byte[] inBuffer = new byte[2];
                        if (ToAscii(MyKeyboardHookStruct.vkCode,
                                  MyKeyboardHookStruct.scanCode,
                                  keyState,
                                  inBuffer,
                                  MyKeyboardHookStruct.flags) == 1)
                        {
                            char key = (char)inBuffer[0];
     
                            if ((isCapslock ^ isShift) && Char.IsLetter(key))
                                key = Char.ToUpper(key);
                            KeyPressEventArgs e = new KeyPressEventArgs(key);
                            _onKeyPress(this, e);
                            handled = handled || e.Handled;
                        }
                    }
     
                    // KeyUp
                    if (_onKeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
                    {
                        Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                        KeyEventArgs e = new KeyEventArgs(keyData);
                        _onKeyUp(this, e);
                        handled = handled || e.Handled;
                    }
     
                }
     
                // si handled est a true, on ne transmet pas le message au destinataire
                if (handled)
                    return 1;
                else
                    return CallNextHookEx(_hook, nCode, wParam, lParam);
            }
     
            #endregion
     
        }
    }
    Merci d'avance,

    Cordialement,
    NeoKript

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Hook souris qui ne fonctionne pas partout
    Par thenaoh dans le forum Windows
    Réponses: 5
    Dernier message: 01/10/2010, 00h57
  2. [SQL] Requête à jointure qui ne fonctionne pas
    Par Bensor dans le forum Langage SQL
    Réponses: 2
    Dernier message: 09/12/2004, 16h10
  3. Jointure externe qui ne fonctionne pas
    Par Guizz dans le forum Langage SQL
    Réponses: 3
    Dernier message: 05/02/2004, 12h26
  4. CREATEFILEMAPPING qui ne fonctionne pas???
    Par Jasmine dans le forum MFC
    Réponses: 2
    Dernier message: 06/01/2004, 19h33
  5. UNION qui ne fonctionne pas
    Par r-zo dans le forum Langage SQL
    Réponses: 7
    Dernier message: 21/07/2003, 10h04

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo