1

I am using Gma.System.MouseKeyHook and getting the following exception:

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.'

I've tried to handle the function calls and subscription. However, the issue still persists. Also I try to run it many times, occasionally it gives a 'NullReferenceException' as well. It also confused me a lot, maybe those issues are correlated.

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) {

    }


}

}

Atakan Atamert
  • 215
  • 2
  • 13

1 Answers1

1
  1. add this: private static IKeyboardMouseEvents HookEvents = null;
  2. use HookEvents.MouseDown replace Hook.GlobalEvents().MouseDown
  • Thank you for those are alternative solutions. What I did to solve is to add additional Subscribe() and Unsubscribe() methods with hooks handled inside them. – Atakan Atamert May 21 '19 at 18:36