2013-03-25 27 views
7

我正在使用這個函數來移動光標。c#可靠MouseMove(hop)

[DllImport("user32.dll")] 
static extern bool SetCursorPos(int X, int Y); 

當我使用熱鍵來觸發它,將光標移動到正確的COORDS和下一次我將它從該位置繼續鼠標。按預期工作。

但是我需要在MouseMove事件期間觸發SetCursorPos。如果用戶將鼠標移動到特定區域,我希望它跳到另一個地方並從那裏繼續。但現在它跳到目的地,然後立即跳回(90%的時間)。我怎樣才能避免這種行爲?

編輯:我決定通過在1個鼠標移動事件中將光標剪切爲1×1的方塊來解決這個問題。 Cursor.Clip(MousePosition,new Rectangle(1,1));

+4

請發佈您的MouseMove事件處理程序代碼。 – 2013-03-25 01:35:18

+0

我真的只是在MouseMove事件中調用該函數而沒有其他操作。 – user1340531 2013-03-25 01:38:32

+0

@ user1340531:無論如何發佈? – mpen 2013-03-25 01:41:03

回答

1

我的猜測是在您想要觸發事件的區域的窗體上還有另一個控件。如果是這樣,控件捕獲MouseMove事件。

例如,在這裏,我在位置0,0的左上角添加了一個綠色的200x200面板。如果鼠標在面板上移動,表單的MouseMove事件將停止捕獲鼠標光標位置。在我的表單的mouse_move事件中,我將窗體的文本設置爲顯示鼠標座標。請注意,當鼠標實際位於0,0時,窗口文本中的座標仍爲200,200(由於必須單擊SnippingTool.exe才能獲取屏幕截圖,因此無法看到我的光標)。

enter image description here

爲了解決這個問題,使用在面板的MouseMove事件放置在你的窗體的MouseMove事件(或任何控制你正在使用)相同的代碼。這將導致表單文本中的正確座標。

enter image description here

這裏是代碼(這可以明顯地重構爲一個方法):

public partial class Form1 : Form 
{ 
    [DllImport("user32.dll")] 
    static extern bool SetCursorPos(int X, int Y); 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_MouseMove(object sender, MouseEventArgs e) 
    { 
     this.Text = string.Format("X: {0}, Y: {1}", e.X, e.Y); 

     if (e.X >= 0 && e.X <= 200) 
     { 
      if (e.Y >= 0 && e.Y <= 200) 
      { 
       SetCursorPos(500, 500); 
      } 
     } 
    } 

    private void panel1_MouseMove(object sender, MouseEventArgs e) 
    { 
     this.Text = string.Format("X: {0}, Y: {1}", e.X, e.Y); 

     if (e.X >= 0 && e.X <= 200) 
     { 
      if (e.Y >= 0 && e.Y <= 200) 
      { 
       SetCursorPos(500, 500); 
      } 
     } 
    } 
} 
+0

我的MouseMove事件實際上是全局性的,只要光標移動,它就會被觸發,而不管我徘徊什麼。 – user1340531 2013-03-25 02:28:08

+2

@ user1340531正如其他評論者所述,您需要將該代碼添加到您的問題中。 – Inisheer 2013-03-25 02:29:39

+1

主要是因爲沒有「全局」MouseMove事件,除非你已經安裝了全局鉤子。 – 2013-03-25 22:53:56

0

很難與這樣的小信息(也許你的GUI的屏幕截圖,將有助於)說。 您可以嘗試:

private void Button_MouseMove_1(object sender, MouseEventArgs e) 
    { 
     SetCursorPos(0, 0); 
     e.Handled = true; 
    }