C#-WinForm-设计时编程【4】-响应鼠标事件
在设计器中,先看效果:
1、鼠标离开
2、鼠标进入(手形光标没截出来)
3、鼠标单击
代码及其分析:
引用命名空间:
1 using System.ComponentModel; 2 using System.ComponentModel.Design; 3 using System.Drawing; 4 using System.Windows.Forms; 5 using System.Windows.Forms.Design; 6 using System.Windows.Forms.Design.Behavior;
第一步:定义一个行为类EventBehavior,这个类继承了Behavior,对需要处理的事件进行重写,用于处理鼠标事件,代码很简单,就不需要解释了,代码如下:
1 class EventBehavior : Behavior 2 { 3 bool isPressed = false; 4 Control control; 5 6 public EventBehavior(Control control) 7 { 8 this.control = control; 9 } 10 11 public override bool OnMouseDown(Glyph g, MouseButtons button, Point mouseLoc) 12 { 13 isPressed = true; 14 return true; 15 } 16 17 public override bool OnMouseUp(Glyph g, MouseButtons button) 18 { 19 if (isPressed) 20 OnClick(); 21 22 isPressed = false; 23 return true; 24 } 25 26 public override bool OnMouseEnter(Glyph g) 27 { 28 this.control.BackColor = Color.LightPink; 29 return true; 30 } 31 32 public override bool OnMouseLeave(Glyph g) 33 { 34 this.control.BackColor = Color.FromKnownColor(KnownColor.Control); 35 return true; 36 } 37 38 public void OnClick() 39 { 40 MessageBox.Show("你单击了我!"); 41 } 42 }
第二步:定义一个EventGlyph类,这个类继承Glyph,实现自定义控件的选择和图像处理,代码如下:
1 class EventGlyph : Glyph 2 { 3 Control control; 4 BehaviorService behaviorSvc; 5 6 public EventGlyph(BehaviorService behaviorSvc, Control control) 7 : base(new EventBehavior(control)) 8 { 9 this.behaviorSvc = behaviorSvc; 10 this.control = control; 11 } 12 13 public override Rectangle Bounds 14 { 15 get 16 { 17 Point edge = behaviorSvc.ControlToAdornerWindow(control); 18 Size size = control.Size; 19 Rectangle bounds = new Rectangle(edge.X, edge.Y, size.Width, size.Height); 20 21 return bounds; 22 } 23 } 24 25 public override Cursor GetHitTest(System.Drawing.Point p) 26 { 27 if (this.Bounds.Contains(p)) 28 { 29 return Cursors.Hand; 30 } 31 32 return null; 33 } 34 35 public override void Paint(PaintEventArgs pe) 36 { 37 TextFormatFlags sf = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis; 38 TextRenderer.DrawText(pe.Graphics, "设计时响应鼠标单击事件哦", this.control.Font, this.Bounds, Color.DarkBlue, Color.Transparent, sf); 39 }
第三步:定义一个设计器EventControlDesigner,它将行为和绘制部分的内容绑定在设计器中,代码如下:
1 public class EventControlDesigner : ScrollableControlDesigner 2 { 3 private ISelectionService SelectionService 4 { 5 get 6 { 7 return this.GetService(typeof(ISelectionService)) as ISelectionService; 8 } 9 } 10 11 public override GlyphCollection GetGlyphs(GlyphSelectionType selectionType) 12 { 13 GlyphCollection glyphs = base.GetGlyphs(selectionType); 14 if (SelectionService != null) 15 { 16 if (SelectionService.PrimarySelection == this.Control) 17 glyphs.Add(new EventGlyph(this.BehaviorService, this.Control)); 18 } 19 return glyphs; 20 } 21 }
第四步:在自定义控件上使用设计器,代码如下:
1 [Designer(typeof(EventControlDesigner))] 2 class EventControl:System.Windows.Forms.Control 3 { 4 }
至此为止,一个可以在设计时响应鼠标事件的控件可以运行了。