简体   繁体   English

C# 如何检测鼠标点击?

[英]C# How do I detect mouse click?

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");

      }
   }
}

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:如果您可以使用 nuGet 软件包,请安装此软件包:https ://www.nuget.org/packages/MouseKeyHook/5.6.0?_src=template 并浏览/修改示例或如下所示:

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. pps。 you can customise it to detect left/right mouse buttons.您可以自定义它以检测鼠标左/右键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM