简体   繁体   English

如何从 C# 中的控制台应用程序设置鼠标 cursor 的 position?

[英]How do I set the position of the mouse cursor from a Console app in C#?

I've found many articles on how to set the mouse position in a C# windows forms project - I want to do this in a console application.我找到了很多关于如何在 C# windows ZAC68B62ABFD6A9FE26E8AC42Z ZAC68B62ABFD6A9FE26E8AC42 中设置鼠标 position 的文章。 How can I set the absolute mouse position from a C# windows console application?如何从 C# windows控制台应用程序设置绝对鼠标 position?

Thanks!谢谢!

Hint: it's not Console.setCursorPosition, that only sets the position of the text cursor in the console.提示:不是Console.setCursorPosition,它只设置控制台中文本cursor的position。

This is an old thread, but for the sake of completion it can be done this way...这是一个旧线程,但为了完成它可以这样做......

use System.Runtime.InteropServices;

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

then in method whatever position you wish eg然后在您希望的任何 position 方法中,例如

  SetCursorPos(500, 500);

Inside your console application, add a reference to System.Windows.Forms.dll and use the other techniques you've read about.在您的控制台应用程序中,添加对 System.Windows.Forms.dll 的引用并使用您读过的其他技术。 The choice of console vs windows exe only impacts the PE header (and maybe the default code template, but you can hack that trivially);控制台与 windows exe 的选择仅影响 PE header(可能是默认代码模板,但您可以轻松破解); you can still use the full framework in a console exe.您仍然可以在控制台 exe 中使用完整的框架。

The mouse you want to control is in windows, not the console.您要控制的鼠标在 windows 中,而不是控制台。

Fixed little mistake in Chaz unswer:修复了 Chaz unswer 中的小错误:

using System.Runtime.InteropServices;


namespace ConsoleImageWorker
{
    public static class Mouse
    {

        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);

        public static void SetCursorPosition(int x, int y)
        {
            SetCursorPos(x, y);
        }
    }
}

After that in any class you can just call:之后在任何 class 中,您可以调用:

Mouse.SetCursorPosition(100, 100);

You can simply assign to Cursor.Position .您可以简单地分配给Cursor.Position

However, in a console application you will need to add references to the WinForms assemblies because console application projects do not include references to WinForms by default.但是,在控制台应用程序中,您需要添加对 WinForms 程序集的引用,因为默认情况下控制台应用程序项目不包含对 WinForms 的引用。

You will need to add System.Windows.Forms and System.Drawing , the latter to gain access to the Point class.您需要添加System.Windows.FormsSystem.Drawing ,后者才能访问Point class。

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

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