2016-03-06 273 views
0

我正在做一個項目來控制鼠標,在下面的代碼中,我有點迷路。this.Cursor not working properly?

我需要聲明的對象命名空間:

using System.Windows; 
using System.Windows.Forms; 
using System.Drawing; 

,並在這裏代碼:

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

它告訴我,光標不會在上下文中存在,但只有在this.Cursor 。同樣適用於this.Locthis.Size。有人知道爲什麼我錯過了一個命名空間嗎?

編輯:確切的代碼:

public class MouseMove 
{ 
    [DllImport("user32.dll")] //TODO add block feature on screens that need it 
    private static extern bool BlockInput(bool block); 

    public static void Main() 
    { 
     this.Cursor = new Cursor(Cursor.Current.Handle); 
     Cursor.Position = new Point(Cursor.Position.X, Cursor.Position.Y); 
     Cursor.Clip = new Rectangle(this.Location, this.Size); 
    } 
} 
+1

你能提供寫代碼的方法和類嗎? – Valentin

+1

你的班級有一個名爲'Cursor'的字段嗎? –

回答

1

PositionClipCursor靜態屬性。您無法使用實例訪問它們。爲了使用靜態變量,您需要使用以下語法:classname.variablename。你的情況的代碼應該類似於:

static void Main(string[] args) 
{ 
    Cursor.Position = new Point(Cursor.Position.X, Cursor.Position.Y); 
    Cursor.Clip = new Rectangle(location, size); 
} 

正如我認爲,你從MSDN花了一個例子,但在本例中有與具有光標形式的WinForm應用程序 - this.Cursor。 並在Cursor.PositionCursor是一個類名稱,而不是一個實例。

private void MoveCursor() 
{ 
    //here Cursor is a form's property 
    this.Cursor = new Cursor(Cursor.Current.Handle); 
    // here Cursor is a class name, Position is a static variable. 
    Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50); 
    // here Cursor is a class name, Clip is a static variable. 
    Cursor.Clip = new Rectangle(this.Location, this.Size); 
} 
1

你在做什麼用自身替換系統的光標...

我建議是這樣的:

public static void Main() 
{ 
    Cursor myCursor = new Cursor(Cursor.Current.Handle); 
    myCursor.Position = new Point(Cursor.Position.X, Cursor.Position.Y); 
    myCursor.Clip = new Rectangle(this.Location, this.Size); 
} 

這樣,它是安全的。但即使如此,我不知道你想要完成什麼......

+1

你不能在Main()中調用'myCursor',因爲'myCursor'不是靜態的 – Sakura

+0

它只是用於我正在製作的遊戲中的一個教程階段,它爲你操作遊標。我所要做的就是讓它移動到我想要的地方。我會試試這個,謝謝 –

+0

@Sakura:正確。感謝您指出了這一點。 – MPelletier