【问题标题】:How to move mouse cursor using C#?如何使用 C# 移动鼠标光标?
【发布时间】:2011-12-24 10:46:55
【问题描述】:

我想每隔 x 秒模拟一次鼠标移动。为此,我将使用一个计时器(x 秒),当计时器滴答作响时,我将移动鼠标。

但是,如何使用 C# 使鼠标光标移动?

【问题讨论】:

  • 这听起来像是你没有告诉我们的问题的一半解决方案,可能有更优雅的解决方案。
  • 很有可能!我们不明白为什么,但屏幕保护程序激活了 10 分钟。但我们投入了 999 分钟:P
  • 那么您应该寻找在应用程序运行时阻止屏幕保护程序激活的解决方案,而不是摆弄鼠标或屏幕保护程序设置。例如。 P/调用SetThreadExecutionState。我怀疑这与屏幕保护程序有关 - 编程的鼠标移动不会重置屏幕保护程序计时器。
  • 如果他和我在同一条船上,那是因为他有一个公司的 GP,如果他的计算机空闲 x num 分钟,就会强制他注销。 ;-)

标签: c# mouse-cursor


【解决方案1】:

看看Cursor.Position Property。它应该可以帮助您入门。

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

【讨论】:

  • 谢谢@JamesHill,我不记得该怎么做,你的例子很好。在我的情况下,我向 x 和 y 添加了一些计算,以使鼠标移动时间相关(每秒像素)
  • 这是 WinForms 方法吗?
  • 我觉得我应该提到这一点,以免有人陷入我刚刚遇到的搞笑问题。 Cursor.Clip 会将鼠标的移动限制在LocationSize 指定的大小。所以上面的 sn-p 只会让你的鼠标在应用程序的边界框内移动。
  • Cursor.Position 如果在virtual machine 中使用,可能需要特定设置。
  • 工作正常,如果 Cursor.Clip 线被删除,它也可以在窗口最小化时工作。
【解决方案2】:

首先添加一个名为 Win32.cs 的类

public class Win32
{ 
    [DllImport("User32.Dll")]
    public static extern long SetCursorPos(int x, int y);

    [DllImport("User32.Dll")]
    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;

        public POINT(int X, int Y)
        {
            x = X;
            y = Y;
        }
    }
}

你可以像这样使用它:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

【讨论】:

  • POINT 类型从何而来?
  • 如何使用这种方法获取鼠标光标位置?
  • 这很好.. 应该注意这是相对于表单的左上角的。所以它与例如使用的坐标相同。表单上的控件,以及用于(并且 - 回答我上面评论中的 q - 可以从)中使用的相同坐标,MouseEventArgs e,例如 Form 的 MouseMove 方法。
  • this.Handle 暗示了一个 WinForm 应用程序,但您可以获得当前运行的 WinForm 进程之外的任何运行窗口的句柄。示例: IntPtr desktopWinHandle = Win32.GetDesktopWindow();其中 GetDesktopWindow 被声明为 [DllImport("user32.dll", SetLastError = false)] public static extern IntPtr GetDesktopWindow();在 Win32 类中。还要检查 Win32 互操作方法 EnumWindows()。 [DllImport("user32.dll")] public static extern int EnumWindows(WndEnumProc lpEnumFunc, int lParam);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多