Search code examples
c#mouse-hook

Disable Right Button (global) in c# like AHK program


I know c# and i want create a fuction for deactive and active mouse left/right button only (in c# code) like a AHK program. Can you help me?


Solution

  • Have a look at https://globalmousekeyhook.codeplex.com/, it has complete facilities for global keyboard and mouse hook.

    the example below is based on mentioned library for mouse right click suppression

    Right Click Suppressor

    using System;
    using System.Windows.Forms;
    using MouseKeyboardActivityMonitor.WinApi;
    
    namespace Demo
    {
        class MouseRightClickDisable:IDisposable
        {
            private readonly MouseHookListener _mouseHook;
    
            public MouseRightClickDisable()
            {
                _mouseHook=new MouseHookListener(new GlobalHooker());
                _mouseHook.MouseDownExt += MouseDownExt;
                _mouseHook.Enabled = true;
            }
    
            private void MouseDownExt(object sender, MouseEventExtArgs e)
            {
                if (e.Button != MouseButtons.Right) { return; }
                e.Handled = true; //suppressing right click
            }
    
    
            public void Dispose()
            {
                _mouseHook.Enabled = false;
                _mouseHook.Dispose();
            }
        }
    }
    

    Usage

    internal static class Program
    {
    
        [STAThread]
        private static void Main()
        {
            using (new MouseRightClickDisable())
                Application.Run();
        }
    }
    

    Console Sample

    NOTE: add System.Windows.Forms.dll as reference to your console application

    internal static class Program
    {
        [STAThread]
        private static void Main()
        {
            Console.WriteLine("Mouse Hook");
    
            // our UI thread here
            var t = new Thread(() =>
            {
                using (new MouseRightClickDisable())
                    Application.Run();
            });
    
            t.Start();
    
            //some console task here!
            for (var i = 0; i < 10; i++)
            {
                Console.WriteLine("Console Task {0}",i);
                Thread.Sleep(100);
            }
    
    
            Console.WriteLine("press any key to terminate the application...");
            Console.ReadKey();
            Application.Exit();
        }
    }