Controls Built from Scratch


If no existing control or group of controls can provide the behavior that you want, you can build a control completely from scratch. Start a new control library project as usual. Give the library a meaningful name and remove the default control UserControl1.

Add a new class, open it in the code editor, and add the statement Inherits Control. Then add whatever code you need to make the control do what you want.

The following code shows how the SimpleSmiley control works. When the control receives a Paint or Resize event, it calls subroutine DrawFace, passing it the Graphics object on which it should draw. Subroutine DrawFace clears the control using the parent’s background color. It then calls a series of Graphics object methods to draw a smiley face on the control’s surface. This drawing code isn’t terribly relevant for this discussion, so it is omitted here to save space.

  <ToolboxBitmap(GetType(SimpleSmiley), "SmileyFaceTool.bmp")> _ Public Class SimpleSmiley     Inherits Control     Private Sub SimpleSmiley_Paint(ByVal sender As Object, _      ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint         DrawFace(e.Graphics)     End Sub     Private Sub SimpleSmiley_Resize(ByVal sender As Object, _      ByVal e As System.EventArgs) Handles Me.Resize         Me.Invalidate()     End Sub     ' Draw the smiley face.     Private Sub DrawFace(ByVal gr As Graphics)         If (Me.ClientSize.Width = 0) Or _            (Me.ClientSize.Height = 0) Then Exit Sub         gr.Clear(Me.BackColor)         gr.SmoothingMode = Drawing2D.SmoothingMode.HighQuality         ' Face.         Dim face_rect As New Rectangle(0, 0, _             Me.ClientSize.Width - 1, _             Me.ClientSize.Height - 1)         gr.FillEllipse(Brushes.Yellow, face_rect)         gr.DrawEllipse(Pens.Black, face_rect)         ' More drawing code omitted...     End Sub End Class  

When you build your own control from scratch, you can make it do just about anything that you like. The obvious drawback is that you need to write code to make it do everything that you want. If there’s already a control that does almost what you need, it will generally be easier to derive a control from that one rather than building one from scratch.

If you can display the data in standard controls such as Label, TextBox, or TreeView controls, it would be easier to build a composite control. If you must display information by drawing it yourself anyway, a composite control won’t help, so you might want to use this kind of control. For example, if you are building a mapping or drafting system, you might want to build a control from scratch to load and display maps and architectural drawings.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net