【问题标题】:Stop or move the mouse停止或移动鼠标
【发布时间】:2010-07-29 13:12:07
【问题描述】:

我有一个图形应用程序,我可以在其中用鼠标移动图形对象。

在某些情况下,对象会停止移动。然后我也需要停止移动鼠标光标。

有可能吗? MousePosition 属性似乎在 ReadOnly 中。

例如。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.X > 100)
        {
            Cursor.Position = new Point(100, Cursor.Position.Y);
        }
    }
}

EDIT,第二个版本,工作,但光标不是“稳定” - 闪烁:

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.X > 100)
        {
            Point mousePosition = this.PointToClient(Cursor.Position);
            mousePosition.X = 100;
            Point newScreenPosition = this.PointToScreen(mousePosition);
            Cursor.Position = newScreenPosition;
        }
    }

【问题讨论】:

  • 您可以用一个对 ClipCursor 的调用来替换此代码,其中矩形是 {0, 0, 100, Form.Height}(显然是从客户端坐标转换为屏幕坐标)。

标签: .net winforms gdi+


【解决方案1】:

您可以通过 PInvoke 使用 ClipCursor 函数。如果边界矩形足够小,鼠标就不会移动。


编辑

一个例子:

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct RECT {
    public int left;
    public int top;
    public int right;
    public int bottom;
};


public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    [DllImport("user32.dll")]
    static extern bool ClipCursor([In()]ref RECT lpRect);

    [DllImport("user32.dll")]
    static extern bool ClipCursor([In()]IntPtr lpRect);


    private bool locked = false;

    private void button1_Click(object sender, EventArgs e)
    {

        if (locked) {
            ClipCursor(IntPtr.Zero );
        }
        else {
            RECT r;

            Rectangle t = new Rectangle(0, 0, 100, this.ClientSize.Height);
            t = this.RectangleToScreen(t);

            r.left = t.Left;
            r.top = t.Top;
            r.bottom = t.Bottom;
            r.right = t.Right;

            ClipCursor(ref r);
        }

        locked = !locked;

    }
    private void Form1_Load(object sender, EventArgs e)
    {

    }
}

【讨论】:

  • e.. .NET 中的用途是什么?
  • “足够小”是什么意思?如果没有?
  • c# 和 vb 的 .net 声明在本文底部。
  • @serhio 这是 .NET 中的用法:pinvoke.net/default.aspx/user32.ClipCursor(它甚至为您提供了所有正确的结构定义)
  • ... 如果没有,光标将在这个矩形内移动。如果矩形有一个像素那么大,光标将冻结。
【解决方案2】:

您是否尝试过使用Cursor.Position

例如

Cursor.Position = new Point(100, 100);

您可以继续将其设置为恒定值(如 Vulcan 所说)。

【讨论】:

  • 我使用 OnMouseMove e As System.Windows.Forms.MouseEventArgs 并且似乎 e.Location 与 Cursor.Position 不同步......而且我在使用它时有可见的光标“反馈”......
  • @serhio 这很奇怪......它有多不同步?
  • @serhio 嗯...不知道从那里去哪里
  • 我找到了原因,但还是不开心,因为闪烁... :)
猜你喜欢
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多