【问题标题】:Get Mouse Cursor position in a C# console app在 C# 控制台应用程序中获取鼠标光标位置
【发布时间】:2020-10-14 15:26:47
【问题描述】:

所以我需要在 C# 控制台应用程序中获取鼠标位置。 不是应用中的光标。就像说光标在屏幕的上角它会输出 0,0。我需要将 X 和 Y 保存到 int 变量中

但鼠标指针在应用程序之外或应用程序中的任何位置。

编辑:

如何获取“GetCursorPos()”(X 和 Y)的值

【问题讨论】:

  • 在 windows 上你可以使用 WINAPI 原生函数 (GetCursorPos)
  • 我需要获取它而不是设置它@МаксимКошевой
  • 是的,但答案是一样的。您可以将 WinForms 库添加到您的项目中并使用 Cursor.Position(它支持 get 和 set),或者使用 WinApi,但不是 SetCursorPos,而是使用 GetCursorPos
  • 如何获取“GetCursorPos()”(X 和 Y)的值

标签: c# .net-core console


【解决方案1】:

这个程序将每1秒获取鼠标在屏幕上的X、Y位置

using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Threading;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                // New point that will be updated by the function with the current coordinates
                Point defPnt = new Point();

                // Call the function and pass the Point, defPnt
                GetCursorPos(ref defPnt);

                // Now after calling the function, defPnt contains the coordinates which we can read
                Console.WriteLine("X = " + defPnt.X.ToString());
                Console.WriteLine("Y = " + defPnt.Y.ToString());
                Thread.Sleep(1000);
            }
        }

        // We need to use unmanaged code
        [DllImport("user32.dll")]

        // GetCursorPos() makes everything possible
        static extern bool GetCursorPos(ref Point lpPoint);
    }
}

Source

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2023-02-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    相关资源
    最近更新 更多