2014-10-10 77 views
0

如何在我的类方法中使用子句句柄。比如我想在picturebox1绘制图像的代码:VB.NET Class方法处理绘画事件

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。对不起英语不好。

+0

PictureBox1是您的Form类的成员,而不是您的Cell类的成员。如果你想保持这种方法,那么你需要一个构造函数来获取PictureBox参数,并使用AddHandler语句来订阅事件。您将很快从Windows窗体编程的入门书中受益,如果您不了解基础知识,则无法走得太远。 – 2014-10-10 10:26:56

+0

[处理在另一个类/文件中定义的对象事件]的可能重复(http://stackoverflow.com/questions/24698988/handle-events-of-object-defined-in-another-class-file) – Plutonix 2014-10-10 11:42:12

回答

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