2

I need to know how to detect a mouse click in a console application (not win forms!). The way I'm trying to do it now is not working.

static void Main (  string [ ] args ) {                

   while(true){

      if (Mouse.LeftButton == MouseButtonState.Pressed){

           Console.WriteLine("Left mouse button was pressed");

      }
   }
}
Zachwuzhere
  • 329
  • 3
  • 12

1 Answers1

1

if you're okay to use nuGet packages then install this one: https://www.nuget.org/packages/MouseKeyHook/5.6.0?_src=template and browse/modify the examples or as below:

using System;
using System.Threading;
using Gma.System.MouseKeyHook;

namespace ConsoleHook
{
    internal class LogMouse
    {
        public static void Do(Action quit)
        {
            Console.WriteLine("Press Q to quit.");
            Hook.GlobalEvents().MouseDown += (sender, e) =>
            {
                Console.Write(e.Button);
            };
            Hook.GlobalEvents().KeyPress += (sender, e) =>
            {
                //Console.Write(e.KeyChar);
                if (e.KeyChar == 'q') quit();
            };
        }
    }
}

ps. it works in a console app. pps. you can customise it to detect left/right mouse buttons.

nemethv
  • 45
  • 7