Results 1 to 8 of 8

Thread: Draw Common "Picture" on All Controls

Threaded View

  1. #1

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Draw Common "Picture" on All Controls

    C# version here.

    The following code uses a single Paint event handler to draw the same "picture" on every control on a form. Specifically it draws a line from the top, left corner of the form to the bottom, right corner and "over" any controls that happen to be on that diagonal.
    VB.NET Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Form1_Load(ByVal sender As System.Object, _
    4.                            ByVal e As System.EventArgs) Handles MyBase.Load
    5.         Dim ctl As Control = Me.GetNextControl(Me, True)
    6.  
    7.         Do Until ctl Is Nothing
    8.             AddHandler ctl.Paint, AddressOf Form1_Paint
    9.             ctl = Me.GetNextControl(ctl, True)
    10.         Loop
    11.     End Sub
    12.  
    13.     Private Sub Form1_Paint(ByVal sender As Object, _
    14.                             ByVal e As PaintEventArgs) Handles Me.Paint
    15.         'Get the points relative to the form.
    16.         Dim start As New Point(0, 0)
    17.         Dim [end] As New Point(Me.ClientSize)
    18.  
    19.         Dim paintee As Control = DirectCast(sender, Control)
    20.  
    21.         'Translate the points relative to the control being painted.
    22.         start = paintee.PointToClient(Me.PointToScreen(start))
    23.         [end] = paintee.PointToClient(Me.PointToScreen([end]))
    24.  
    25.         e.Graphics.DrawLine(Pens.Black, start, [end])
    26.     End Sub
    27.  
    28. End Class
    You can use a similar pattern to draw any "picture" you like on your form. The important part is the use of PointToScreen and PointToClient to convert coordinates from the form's frame of reference to that of the control currently being painted.

    Note also that you can attach the event handler to your controls any way you like. The code I've included in the Load event handler there means that any controls you add in the designer will be included. Alternatively you could include the other controls in the method's Handles clause along with the form. You can also use the AddHandler statement to include controls added at run time.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width