Drawing a string

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,
I've got a little problem. I want to draw a string to my form with the
follówing code:

Public Sub titleSetTime(ByVal newTime As String)
Dim g As System.Drawing.Graphics
g.DrawString(newTime, New System.Drawing.Font("Microsoft Sans
Serif", 10, System.Drawing.FontStyle.Regular), New
SolidBrush(SystemColors.ControlText), 200, 2)
End Sub

But if I try this, I get a SystemNullReferenceExeption. Does sombody know why?

Thx,
Cyberdot
 
Cyberdot said:
Hello,
I've got a little problem. I want to draw a string to my form with the
follówing code:

Public Sub titleSetTime(ByVal newTime As String)
Dim g As System.Drawing.Graphics
g.DrawString(newTime, New System.Drawing.Font("Microsoft Sans
Serif", 10, System.Drawing.FontStyle.Regular), New
SolidBrush(SystemColors.ControlText), 200, 2)
End Sub

But if I try this, I get a SystemNullReferenceExeption. Does sombody know why?

You haven't actually created a Graphics object, you've just declared
one. I suggest you override the OnPaint method of your form, and use the
Graphics object provided to you in the PaintEventArgs parameter. Check
the MSDN documentation for details.
 
Because you haven't instantiated g, just created a variable to hold a
Graphics object. You can use

g = Me.CreateGraphics()

To get the Graphics instance for your form, which you will then be able to
draw with. You would probably be best to add this drawing code into your
OnPaint override for the form, then invalidate the form when the value
changes.

Peter

--
Peter Foot
Windows Embedded MVP
www.inthehand.com | www.opennetcf.org

Do have an opinion on the effectiveness of Microsoft Windows Mobile and
Embedded newsgroups? Let us know!
https://www.windowsembeddedeval.com/community/newsgroups
 
Yeah, I tried it and it works. But now I have another problem. I have a
picturebox on the same position where I want to draw the string, and it looks
like the picture box is in front of the string I've drawn. Is there a method
to get the graphics handler for a picturebox?

Thx,
Cyberdot
 
If all you want to do is draw in teh picturebox then :

Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As
System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
Dim g As Graphics = e.Graphics
g.DrawString("TEST", New Font("Arial", 12, FontStyle.Bold), New
SolidBrush(Color.Black), 1, 1)
End Sub

will do it

Steven
 
It is also worth mentioning that creating a new font to draw a string every
time is a bad practice - create the font once and reuse it. Same applies to
brushes and other GDI objects
 
Back
Top