ElektroStudios
ElektroStudios

Reputation: 20474

Get the ownercontrol of a graphics object?

Is possible to know the ownercontrol of a Graphics object?

In this method I'm passing the graphics object of a control to a custom method, together with the control's width and height:

Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _
Handles PictureBox1.Paint

    Me.MyMethod(g:=e.Graphics, Width:=sender.width, Height:=sender.height)

End Sub

But I would like to avoid passing the width and height parametters to my method (or else passing the control), instead that MyMethod should find the control width/hight just with the graphics object, in case this could be possibly.

Something like this pseudocode:

private sub mymethod(byval g as graphics)

    dim _width as integer = g.GetControlWidth
    dim _height as integer = g.GetontrolHeight

end sub

Upvotes: 0

Views: 84

Answers (1)

Your question has a flaw in its premise: just because you acquire the Graphics object in a control's paint event, doesnt mean they are related or that you can get the control from Graphics. System.Drawing.Graphics is just not directly related to Control. About as close as you can get is:

MyMethod(g As Graphics, ctl As Control) 

Even then, for many other painting and drawing events, you will lose other vital information in those e As xxxEventArgs such as e.DrawBackGround, e.DrawFocusRect, e.ClipRectangle (sometimes more important than the control's size) e.PaintParentBackground and so forth.

There are times when you can call a common procedure - such as drawing a 3D rectangle, or borders etc - but those are usually of value when a procedure depends on one or more calculated args common to each control or thing being painted/Drawn:

Protected Sub Draw3DRect(g As Graphics, rect As Rectangle, bRaised As Boolean)

Protected Sub DrawBorder(g As Graphics, R As Rectangle)

Private Sub DrawThumb(g As Graphics, R As Rectangle)

The actual drawing or painting of whatever is all the same once the Rectangle is defined, but the Rectangle is not necessarily related to the Control's Size.

Upvotes: 1

Related Questions