Global Hook Keylogger problem
Asked Answered
D

1

7

It logs the keys to textbox currently so its safe.

PROBLEM The problem is when i run this at virtual machine, or my friends laptop, it hangs after pressing certain amount of keys(random).It runs perfectly fine in mine.

http://i34.tinypic.com/29o1im8.jpg

class GlobalKeyboardHook
{


    #region Definition of Structures, Constants and Delegates

    public delegate int KeyboardHookProc(int nCode, int wParam, ref GlobalKeyboardHookStruct lParam);

    public struct GlobalKeyboardHookStruct
    {
        public int vkCode;
        public int scanCode;
        public int flags;
        public int time;
        public int dwExtraInfo;
    }

    const int WM_KEYDOWN = 0x100;
    const int WM_KEYUP = 0x101;
    const int WM_SYSKEYDOWN = 0x104;
    const int WM_SYSKEYUP = 0x105;
    const int WH_KEYBOARD_LL = 13;

    #endregion

    #region Events

    public event KeyEventHandler KeyDown;
    public event KeyEventHandler KeyUp;

    #endregion

    #region Instance Variables

    public List<Keys> HookedKeys = new List<Keys>();
    IntPtr hookHandle = IntPtr.Zero;

    #endregion

    #region DLL Imports

    [DllImport("kernel32.dll")]
    static extern IntPtr LoadLibrary(string lpFileName);

    [DllImport("user32.dll", CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    static extern IntPtr SetWindowsHookEx(int hookID, KeyboardHookProc callback, IntPtr hInstance, uint threadID);

    [DllImport("user32.dll", CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    static extern bool UnhookWindowsHookEx(IntPtr hookHandle);

    [DllImport("user32.dll", CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall)]
    static extern int CallNextHookEx(IntPtr hookHandle, int nCode, int wParam, ref GlobalKeyboardHookStruct lParam);




    #endregion

    #region Public Methods

    public int hookProc(int nCode, int wParam, ref GlobalKeyboardHookStruct lParam)
    {

        if (nCode >= 0)
        {
            Keys key = (Keys)lParam.vkCode;

            if (HookedKeys.Contains(key) == true)
            {
                KeyEventArgs kea = new KeyEventArgs(key);

                    if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && KeyUp != null)
                    {
                        KeyUp(this, kea);
                    }
                    else if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && KeyDown != null)
                    {
                        KeyDown(this, kea);
                    }
                    if (kea.Handled) return 1;


            }
        }

     return CallNextHookEx(hookHandle, nCode, wParam, ref lParam);
    }


    public void hook()
    {
            IntPtr hInstance = LoadLibrary("user32");
            hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);
    }


    public void unhook()
    {
        UnhookWindowsHookEx(hookHandle);
    }

    #endregion

    #region Constructors and Destructors

    public GlobalKeyboardHook()
    {
        hook();
    }

    ~GlobalKeyboardHook()
    {
        unhook();
    }

    #endregion
Devastate answered 22/8, 2010 at 7:30 Comment(4)
Could you please be a little more specific? Like, where does it hang, when? Any error messages? Could you edit your questions with a minimal code example that reproduces the problem?. And try to make it a question.Jarrettjarrid
Sir there seem to be no runtime error. So ive no idea which part of the code prroduces the problem. Take a look at the file i linked. It has the picture of the error -> "Keylogger is not responding".Devastate
Well you may attach a debugger and break the process to look where it is.Jarrettjarrid
The link points to some zip file downloading stuff. You need to make it easier to read your questions if you want someone to bother reading. Edit the question, insert picture and relevant code parts. If you don't know what parts are relevant you have way to much code for a question. Then you need to simplify the code to the bare minimum to reproduce your problem.Jarrettjarrid
C
10

Try debugging your application with the "CallbackOnCollectedDelegate" MDA turned on (Debug -> Exceptions -> Managed Debugging Assistants -> check "CallbackOnCollectedDelegate").

The common bug here is that the delegate for your hook procedure is automatically collected by the GC after you set the hook (it gets created as part of the P/Invoke marshaling to SetWindowsHookEx). After the GC collects the delegate, the program crashes when trying to call the callback. This would also explain the randomness.

If this is your issue, you'll see an error like the following:

A callback was made on a garbage collected delegate of type '...'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.

Try keeping a reference to your hook procedure as a member in your class, e.g.:

public delegate int KeyboardHookProc(int nCode, int wParam, ref GlobalKeyboardHookStruct lParam);

public int hookProc(int nCode, int wParam, ref GlobalKeyboardHookStruct lParam)
{
    // ...
}

public void hook()
{
    _hookProc = new KeyboardHookProc(hookProc);
    IntPtr hInstance = LoadLibrary("user32");
    hookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, hInstance, 0);
}

KeyboardHookProc _hookProc;
Curzon answered 22/8, 2010 at 10:39 Comment(1)
Care to accept the answer? It helps others who have similar issues and encourages others to participate. Thanks :)Curzon

© 2022 - 2024 — McMap. All rights reserved.