简体   繁体   中英

Graphics Object in vb.net

I just started creating graphics in vb.net. I created a windows form and double clicked on it. I then got a method which was Form Load method. In this method i wrote the following code.

    Dim g As Graphics
    g = Me.CreateGraphics

    Dim pencolor As New Pen(Color.Red)
    g.DrawLine(pencolor, 10, 20, 100, 200)

I know that Graphics must be created in Paint event. But i am trying to display them in the Form Load Event. For some reason i don't see the output What could possibly be the problem..??

Don't use CreateGraphicsever . I don't think it actually has a legitimate use-case.

Your problem is that you paint something on the form but it's over-written as soon as the next redrawing of the form is triggered because graphics you create that way are not persisted.

You essentially have to use the Paint event (or the OnPaint method) for drawing, there's no way around this. If you want to trigger a redraw in Form_Load you can simply call Me.Invalidate (but I think that should be redundant).

Inside the OnPaint method (or the Paint event), use the Graphics object provided in the parameters:

Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
    MyBase.OnPaint(e) ' First, let the base class do its thing

    Dim g = e.Graphics

    Using p As New Pen(Color.Red)
        g.DrawLine(…)
    End Using
End Sub 

(Notice that Pen is a disposable resource and as such you should wrap it in a Using block.)

Try this:

Public Class Form1

    Dim painted As Boolean = False

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)
        If Not painted Then
            painted = True
            e.Graphics.Clear(Color.Blue)
        End If
    End Sub

End Class

I have extended this nice answer in VB.net (2010) to deal with autosizing of the text in a DataGridView control.

First, modify the function to be:

Private Function MeasureTextWidth(ByVal c As Control, ByVal text As String) As Integer
    If (c Is DBNull.Value) Then
        Return -1
    Else
        Dim g As Graphics = c.CreateGraphics
        Return CInt(Math.Ceiling(g.MeasureString(text, c.Font).Width))
    End If
End Function

The next portion, in the software that calls this function is like this:

    With frm_Parameters_FITs
        .Show()
        With .DataGridView1
            .SuspendLayout()
            .DataSource = Nothing '  CRITICAL
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToResizeRows = False
            .AllowUserToOrderColumns = True
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .ReadOnly = True
            .MultiSelect = False
            .RowHeadersVisible = False
            .Columns.Clear()
            .Rows.Clear()
            ' setup columns
            .Columns.Add("Item", "Item#")
            .Columns(0).Width = 11
            .Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
            .Columns.Add("Parameter", "gHeaderTitle") ' (ColName, HeaderText)
            .Columns(1).Width = 25
            .Columns(1).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
            .Columns.Add("ParamValue", "gHeaderInfo")
            .Columns(2).Width = 40
            .Columns(2).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable
            .Columns.Add("Comments", "gHeaderComment")
            .Columns(3).Width = 50
            .Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .Columns(3).SortMode = DataGridViewColumnSortMode.NotSortable
            .Columns.Add("Comments", "Comments")
            .Columns(4).Width = 60
            .Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .Columns(4).SortMode = DataGridViewColumnSortMode.NotSortable
            .ResumeLayout(True)
        End With
        'Then you can add the data in rows to the cells of the DataGridView:
        Dim piIndex As Integer ' this is a row pointer
        Dim ColTextWidth(5) As Integer
        Dim TextToMeasure As String
        Dim IntTextWidthPixels As Integer

        With .DataGridView1
            For i As Integer = 1 To Globals.giHeaderLines
                .Rows.Add() ' increases the rows.count...the last index is (rows.count-1)
                piIndex = .Rows.Count - 1  ' pointer to the last row just added
                .Rows(piIndex).Cells(0).Value = i.ToString ' puts this text into the col 0 cell

                .Rows(piIndex).Cells(0).Style.WrapMode = DataGridViewTriState.True
                .Rows(piIndex).Cells(1).Value = gHeaderTitle(i)
                .Rows(piIndex).Cells(2).Value = gHeaderInfo(i)
                .Rows(piIndex).Cells(3).Value = gHeaderComment(i)
                .Rows(piIndex).Cells(4).Value = gHeaderComment(i)
                ' now determine the correct col width
                For j As Integer = 0 To 4
                    Try
                        TextToMeasure = .Rows(piIndex).Cells(j).Value
                        IntTextWidthPixels = MeasureTextWidth(frm_Parameters_FITs.DataGridView1, TextToMeasure)

                        If IntTextWidthPixels > ColTextWidth(j) Then
                            ColTextWidth(j) = IntTextWidthPixels
                        End If
                    Catch ex As Exception
                        Debug.Print("Error here in Class_FileIO_FITs. PutDataIntoHeaderDataGrid")
                    End Try
                Next j
            Next i
            ' now reset the cols to the correct width
            For j As Integer = 0 To 4
                .Columns(j).Width = ColTextWidth(j)
            Next j
        End With
        'make sure the row we added is visible
        .DataGridView1.FirstDisplayedScrollingRowIndex = piIndex
        .DataGridView1.ClearSelection()
        .DataGridView1.Rows(piIndex).Selected = True
        .Refresh()
    End With

This works fine to provide the DataGridView control with correctly wide columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM