VB.NET类方法处理绘制事件

时间:2014-10-10 09:43:54

标签: vb.net

如何在我的类方法中使用句柄Handles。例如,我想在picturebox1上使用代码:

绘制图像
Public Class cell
    Public Sub draw_cell() Handles picturebox1.paint
       code
    End Sub
End Class

我有一个错误:

Handles clause requires a WithEvents variable defined in the containing type or one of its base types.

如何在不使用

的情况下执行此操作
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint

PS。抱歉英语不好。

1 个答案:

答案 0 :(得分:0)

您可以创建自己的例程来绘制到画布。

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim canvas As New Bitmap(PictureBox1.Width, PictureBox1.Height)
        Dim canvasGraphics As Graphics = Graphics.FromImage(canvas)
        Dim cellRect As New Rectangle(100, 100, 100, 100)
        cell.draw(canvasGraphics, cellRect, Color.Red, New Pen(New SolidBrush(Color.Green), 1))
        PictureBox1.Image = canvas
    End Sub
    Public Class cell
        Public Shared Sub draw(ByRef canvasGraphics As Graphics, ByVal cellRect As Rectangle, ByVal fillColor As Color, ByVal borderPen As Pen)
            Dim renderedCell As New Bitmap(cellRect.Width, cellRect.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            Dim borderRect As New Rectangle(0, 0, cellRect.Width - 1, cellRect.Height - 1)
            Dim context As BufferedGraphicsContext
            Dim bGfx As BufferedGraphics
            context = BufferedGraphicsManager.Current
            context.MaximumBuffer = New Size(cellRect.Width + 1, cellRect.Height + 1)
            bGfx = context.Allocate(Graphics.FromImage(renderedCell), New Rectangle(0, 0, cellRect.Width, cellRect.Height))
            Dim g As Graphics = bGfx.Graphics
            g.Clear(fillColor)
            g.DrawRectangle(borderPen, borderRect)
            bGfx.Render()
            canvasGraphics.DrawImage(renderedCell, cellRect.Location)
        End Sub
    End Class
End Class