2016-11-23 78 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; 
      } 
     } 
    } 
相关问题