首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在c#中获取鼠标位置

在c#中获取鼠标位置
EN

Stack Overflow用户
提问于 2009-08-23 02:34:54
回答 11查看 389.4K关注 0票数 122

如何获取鼠标位置?我想要它在屏幕位置方面。

我启动我想要设置到当前鼠标位置的程序。

代码语言:javascript
复制
Location.X = ??
Location.Y = ??

编辑:必须在创建表单之前执行此操作。

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2009-08-22 18:41:28

您应该使用System.Windows.Forms.Cursor.Position:“表示光标在屏幕坐标中的位置的点。”

票数 194
EN

Stack Overflow用户

发布于 2011-04-07 15:36:16

如果你不想引用表单,你可以使用interop来获取光标位置:

代码语言:javascript
复制
using System.Runtime.InteropServices;
using System.Windows; // Or use whatever point class you like for the implicit cast operator

/// <summary>
/// Struct representing a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
    public int X;
    public int Y;

    public static implicit operator Point(POINT point)
    {
        return new Point(point.X, point.Y);
    }
}

/// <summary>
/// Retrieves the cursor's position, in screen coordinates.
/// </summary>
/// <see>See MSDN documentation for further information.</see>
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);

public static Point GetCursorPosition()
{
    POINT lpPoint;
    GetCursorPos(out lpPoint);
    // NOTE: If you need error handling
    // bool success = GetCursorPos(out lpPoint);
    // if (!success)
        
    return lpPoint;
}
票数 96
EN

Stack Overflow用户

发布于 2009-08-22 18:47:02

Cursor.Position将获得鼠标的当前屏幕位置(如果您在Control中,MousePosition属性也将获得相同的值)。

要设置鼠标位置,您必须使用Cursor.Position并给它一个新的Point

代码语言:javascript
复制
Cursor.Position = new Point(x, y);

您可以在创建表单之前在Main方法中执行此操作。

票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1316681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档