2010-07-29 133 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