大家写程序的时候,都会遇到现有控件不能满足要求的问题,这时需要借助第三方控件或者自己重新改写现有控件。前者就不多说了,网上找,公司里找,同学中找。如果是自己写呢?我的体会如下:
1.看清需求。知道自己想做什么,需要完成什么样的功能。拿下面代码举例:需求-toolbarbutton必须为可用;当左键点击toolbarbutton时,由主程序来通过一些条件(如用户是否按照规定的步骤操作)判断是否忽略该消息,忽略消息后界面应该没有任何变化。
2.寻找差距。找出自己想要的功能和现有控件的差别。拿下面代码举例:现有控件toolbar中,只要左键点击可用的toolbarbutton,该button都会有所反映;而需求是不让它有反应。
3.寻找现有控件如何实现差距。拿下面代码举例:toolbar在绘制过程中没有使用可重写的onpaint方法,所以重写onpaint方法不能完成需求。在哪能提取到重绘的信息呢?WndProc。
4.设计好类的接口。之所以我们要重写现有控件,是因为我们要使用它现在没有的功能,所以把接口设计好,对以后的修改大有裨益。拿下面代码举例:提供给主程序的事件参数中就包含了toolbarbuttons,可能以后主程序要根据鼠标的左右键作一些判断,或修改一些外观。
5.开始编码。尽量规范,以便以后修改、查看。
代码如下:
Public Class clsToolBar
Inherits ToolBar
Public Event PreviewButtonClick As PreviewButtonClickHandler
Private m_blnCanDown As Boolean = True
Private Function ZGetMouseDownButton(ByVal point As Point) As ToolBarButton
For Each _tbtn As ToolBarButton In Me.Buttons
If _tbtn.Rectangle.Contains(point) Then
Return _tbtn
End If
Next
Return Nothing
End Function
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = CInt(&H201) OrElse m.Msg = CInt(&H203) Then‘鼠标左键为&H201,双击为&H203
Dim _point As Point = Me.PointToClient(Me.MousePosition)
Dim _tbtnTemp As ToolBarButton = ZGetMouseDownButton(_point)
If Not _tbtnTemp Is Nothing Then
Dim _args As New MyButtonClickEventArgs(MouseButtons.Left, _tbtnTemp)
RaiseEvent PreviewButtonClick(Me, _args)
If _args.Cancel Then
m_blnCanDown = False
Exit Sub
End If
End If
End If
If m.Msg = CInt(&HF) Then'重画为&HF
If m_blnCanDown = False Then
Exit Sub
End If
End If
If m.Msg = CInt(&H200) Then'移动鼠标为&H200
m_blnCanDown = True
End If
MyBase.WndProc(m)
End Sub
End Class
Public Delegate Sub PreviewButtonClickHandler(ByVal s As Object, ByVal e As MyButtonClickEventArgs)
Public Class MyButtonClickEventArgs
Private m_blnCancel As Boolean = False
Private m_btnClick As MouseButtons
Public Property Cancel() As Boolean
Get
Return Me.m_blnCancel
End Get
Set(ByVal Value As Boolean)
Me.m_blnCancel = Value
End Set
End Property
Public ReadOnly Property MouseButton() As MouseButtons
Get
Return Me.m_btnClick
End Get
End Property
Public ToolBarButton As ToolBarButton
Public Sub New(ByVal MouseButton As MouseButtons, ByVal button As ToolBarButton)
Me.m_btnClick = MouseButton
Me.ToolBarButton = button
End Sub
End Class