2016-11-23 28 views
1

我嘗試將事件處理程序添加到從.NET類「Panel」繼承的personnal類。在運行時在類上添加MouseDown和MouseMove事件

我嘗試了一些幾種方法可以做到這一點,但它不工作了...

我有一個包含其他小組的首席面板。這是設計Grafcet。

所以,我有我的課「Etape酒店」,從面板繼承:

class Etape : Panel 
    { 
     private Point MouseDownLocation; 

     private void Etape_MouseDown(object sender, MouseEventArgs e) 
     { 
      if (e.Button == MouseButtons.Left) 
      { 
       MouseDownLocation = e.Location; 
       this.BackColor = CouleurSelect; 
       MessageBox.Show("Bonjour"); 
      } 
     } 

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

而且我宣佈會這樣:

toto = new Etape(); 
toto.BackColor = Color.White; 
toto.BorderStyle = BorderStyle.FixedSingle; 
toto.Width = 40; 
toto.Height = 40; 

「TOTO」被添加到我的「主要」面板剛之後。 我想添加一個事件處理程序來在運行時移動我的面板。我試過了上面可以看到的代碼,但我認爲C#沒有檢測到我點擊了Etape。

你有什麼想法或什麼來幫助我嗎?

朱利安

回答

2

應覆蓋OnMouseXXX方法:

class Etape : Panel 
{ 
    private Point MouseDownLocation; 

    protected override void OnMouseDown(MouseEventArgs e) 
    { 
     base.OnMouseDown(e); 

     if (e.Button == MouseButtons.Left) 
     { 
      MouseDownLocation = e.Location; 
      this.BackColor = CouleurSelect; 
      MessageBox.Show("Bonjour"); 
     } 
    } 

    protected override void OnMouseMove(MouseEventArgs e) 
    { 
     base.OnMouseMove(e); 

     if (e.Button == MouseButtons.Left) 
     { 
      this.Left = e.X + this.Left - MouseDownLocation.X; 
      this.Top = e.Y + this.Top - MouseDownLocation.Y; 
     } 
    } 
} 

僅定義了一個名爲Etape_MouseMove()不連接什麼東西給它的方法。

+0

非常感謝你的幫助。這就是我需要的!我會記住「只要聲明一個名爲Etape_MouseMove()的方法就不會掛鉤任何內容。」 –

0

您需要掛鉤函數的事件

class Etape : Panel 
    { 
     public Etape() 
     { 
      MouseDown += Etape_MouseDown; 
      MouseMove += Etape_MouseMove; 
     } 

     private Point MouseDownLocation; 

     private void Etape_MouseDown(object sender, MouseEventArgs e) 
     { 
      if (e.Button == MouseButtons.Left) 
      { 
       MouseDownLocation = e.Location; 
       this.BackColor = CouleurSelect; 
       MessageBox.Show("Bonjour"); 
      } 
     } 

     private void Etape_MouseMove(object sender, MouseEventArgs e) 
     { 
      if (e.Button == MouseButtons.Left) 
      { 
       this.Left = e.X + this.Left - MouseDownLocation.X; 
       this.Top = e.Y + this.Top - MouseDownLocation.Y; 
      } 
     } 
    } 
相關問題