2013-09-30 86 views
1

你好,我發現這個代碼可能會幫助我解決以下問題,我試圖通過鼠標在我的窗體中拖動,拖放和移動標籤。通過鼠標在窗體中抓取,移動和放置控件

private Point MouseDownLocation; 

    private void MyControl_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      MouseDownLocation = e.Location; 
     } 
    } 

    private void MyControl_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      this.Left = e.X + this.Left - MouseDownLocation.X; 
      this.Top = e.Y + this.Top - MouseDownLocation.Y; 
     } 
    } 

但是,當我assing鼠標移動和鼠標按下爲事件標記,我試圖抓住標籤和鼠標將其與整個窗體移動移動。

請問在哪裏應該改進代碼?

謝謝你的時間。

回答

2

而不是使用this.Left(這是形式),你需要將你的控制:

private void MyControl_MouseMove(object sender, MouseEventArgs e) 
{ 
    if (e.Button == System.Windows.Forms.MouseButtons.Left) 
    { 
     MyControl.Left = e.X + MyControl.Left - MouseDownLocation.X; 
     MyControl.Top = e.Y + MyControl.Top - MouseDownLocation.Y; 
    } 
} 

另外,你可能想捕捉按鈕按下鼠標,然後鬆開按鈕了。這將防止「打破」你的邏輯的非常快的動作。詳情請參閱Mouse Capture in Windows Forms