MouseKeyHook 'CallbackOnCollectedDelegate' 问题

MouseKeyHook 'CallbackOnCollectedDelegate' Issue

我正在使用 Gma.System.MouseKeyHook 并收到以下异常:

Managed Debugging Assistant 'CallbackOnCollectedDelegate' Message=Managed Debugging Assistant 'CallbackOnCollectedDelegate' : 'A callback was made on a garbage collected delegate of type 'Gma.System.MouseKeyHook!Gma.System.MouseKeyHook.WinApi.HookProcedure::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.'

我已经尝试处理函数调用和订阅。但是,问题仍然存在。我也多次尝试 运行,偶尔它也会给出 'NullReferenceException'。这也让我很困惑,也许这些问题是相关的。

using Gma.System.MouseKeyHook;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;



// Uses a MouseKeyHook Library license at 
https://github.com/gmamaladze/globalmousekeyhook/blob/master/LICENSE.txt

namespace TransparentClickTest {
public partial class Form1 : Form {


    public Form1() {
        //GC.TryStartNoGCRegion(100);
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        BackColor = Color.Red;
        TransparencyKey = Color.Red;
        InitializeComponent();

        OnDown();            

    }
    protected virtual void OnUp() {
        Hook.GlobalEvents().MouseUp += (sender, e) => {
            try {
                label1.Text = "Mouse Up!!!";
                Hook.GlobalEvents().Dispose();
                OnDown();
            }
            catch(Exception e2) {
                Hook.GlobalEvents().Dispose();
                OnDown();                   
            }
        };
    }

    protected virtual void OnDown() {
        Hook.GlobalEvents().MouseDown += (sender, e) => {
            try {
                label1.Text = $"Mouse {e.Button} Down at {e.X}, {e.Y}";
                Opacity = 1;
                Hook.GlobalEvents().Dispose();
                OnUp();
            }
            catch(Exception e1) {
                Hook.GlobalEvents().Dispose();
                OnUp();
            }
        };
    }

    private void PictureBox1_Click(object sender, EventArgs e) {

    }

    private void Label1_Click(object sender, EventArgs e) {

    }


}

}

  1. 添加:private static IKeyboardMouseEvents HookEvents = null;
  2. 使用HookEvents.MouseDown替换Hook.GlobalEvents()。鼠标按下