Zachwuzhere
Zachwuzhere

Reputation: 489

C# How do I detect mouse click in a Console application?

I need to know how to detect a mouse click in a Console Application (not WinForms!). 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");
        }
    }
}

Upvotes: 2

Views: 3125

Answers (2)

Bachi
Bachi

Reputation: 60

Maybe something like this:

// --------------------- Program.cs ---------------------
using System.Runtime.InteropServices;

MouseClickHandler.StartMouseClickHandling();

// --------------------- Declaration --------------------
class MouseClickHandler
{
  const int LEFT_BTN = 0x01;
  const int RIGHT_BTN = 0x02;
  const int MIDDLE_BTN = 0x04;
  const int KEY_PRESSED_FLAG = 0x8001;

  public static void StartMouseClickHandling()
  {
    while (true)
    {
      if (MouseButtonClicked(LEFT_BTN))
      {
        Console.WriteLine($"Left mouse clicked!");
        WaitUntilMouseButtonReleased(LEFT_BTN);
      }

      if (MouseButtonClicked(MIDDLE_BTN))
      {
        Console.WriteLine($"Middle mouse clicked!");
        WaitUntilMouseButtonReleased(MIDDLE_BTN);
      }

      if (MouseButtonClicked(RIGHT_BTN))
      {
        Console.WriteLine($"Right mouse clicked!");
        WaitUntilMouseButtonReleased(RIGHT_BTN);
      }
    }
  }

  private static void WaitUntilMouseButtonReleased(int MOUSE_BTN)
  {
    while (MouseButtonClicked(MOUSE_BTN))
      Thread.Sleep(10);
  }

  private static bool MouseButtonClicked(int BTN)
  {
    [DllImport("user32.dll", SetLastError = true)]
    static extern short GetAsyncKeyState(int vKey);
    return (GetAsyncKeyState(BTN) & KEY_PRESSED_FLAG) != 0;
  }
}

Upvotes: -1

nemethv
nemethv

Reputation: 47

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.

Upvotes: 1

Related Questions