0

I want to write an application that counts number of mouse clicks in windows. After some research I have found this library: MouseKeyHook I have created wpf application and copied the example code:

public partial class MainWindow : Window
{
    private IKeyboardMouseEvents m_GlobalHook;

    public MainWindow()
    {
        InitializeComponent();
        Subscribe();
    }

    public void Subscribe()
    {
        // Note: for the application hook, use the Hook.AppEvents() instead
        m_GlobalHook = Hook.GlobalEvents();

        m_GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
        m_GlobalHook.KeyPress += GlobalHookKeyPress;
    }

    private void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
    {
        Console.WriteLine("KeyPress: \t{0}", e.KeyChar);
    }

    private void GlobalHookMouseDownExt(object sender, MouseEventExtArgs e)
    {
        Console.WriteLine("MouseDown: \t{0}; \t System Timestamp: \t{1}", e.Button, e.Timestamp);

        // uncommenting the following line will suppress the middle mouse button click
        // if (e.Buttons == MouseButtons.Middle) { e.Handled = true; }
    }

    public void Unsubscribe()
    {
        m_GlobalHook.MouseDownExt -= GlobalHookMouseDownExt;
        m_GlobalHook.KeyPress -= GlobalHookKeyPress;

        //It is recommened to dispose it
        m_GlobalHook.Dispose();
    }
}

There are no errors or warnings, and the application detects clicks and keys typed. But after few clicks I get the error message:

enter image description here

Sometimes this error shows after after just a few clicks, sometimes after 100 clicks (MouseDown event - left mouse button). Also when the error occures my cursor slow down significantly for couple of seconds.

user3662546
  • 87
  • 12
  • Please to show more details about error click on `View Details` link on bottom of page and then paste error message inside inner exception filed to here. – Alireza Jul 12 '15 at 11:09
  • 1
    This MDA had a knack for false warnings, haven't seen it in a long time. Use Debug > Exceptions > Managed Debugging Assistants > LoaderLock and untick the Thrown checkbox. See what hits the fan next, if anything. Real problem probably has something to do with your anti-malware protection, they generally don't like keyloggers that much. – Hans Passant Jul 12 '15 at 11:10
  • @HansPassant your solution works. I have changed this LoaderLock exception to not throw and now my app works without any errors. Thanks! – user3662546 Jul 12 '15 at 11:52

1 Answers1

0

Try to create that Hook object in different thread than main. This problem often occurs with code that runs in DllMain and which blocks GUI.

Immons
  • 257
  • 1
  • 11