2014-10-10 79 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