2010-07-29 132 views
0

我有一个图形应用程序,用鼠标移动图形对象。停止或移动鼠标

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

可能吗? 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); 
     } 
    } 
} 

编辑,第二版,工作,但光标不是 “稳定” - 闪烁:

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; 
     } 
    } 
+0

可以与到ClipCursor函数,其中,所述矩形是一个单一的呼叫替换此代码'{0,0,100,Form.Height}' (显然,从客户端坐标转换为屏幕坐标)。 – GSerg 2010-07-29 13:38:45

回答

3

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


EDIT

一个例子:

[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) 
    { 

    } 
} 
+0

电子..用法是什么。净? – serhio 2010-07-29 13:29:57

+0

你是什么意思“足够小”?如果不? – serhio 2010-07-29 13:30:47

+0

c#和vb的.net声明位于本文的底部。 – GSerg 2010-07-29 13:31:37

2

您是否尝试过使用Cursor.Position

E.g.

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

你可以继续设置它为一个常数值(如Vulcan说的)。

+0

不错!没有意识到这一点。 – 2010-07-29 13:28:03

+0

我使用OnMouseMove e作为System.Windows.Forms.MouseEventArgs 似乎e.Location不与Cursor.Position同步...当使用它时,我也有可见的光标“反馈”... – serhio 2010-07-29 13:28:08

+0

@serhio这很奇怪...它是如何失步的? – NickAldwin 2010-07-29 13:30:27