按钮画线vb.net不工作?

时间:2013-04-22 12:00:22

标签: vb.net button line draw

我正在尝试使用无法正常工作的按钮创建一条线。

如果我使用以下代码,

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms

  Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
      Dim g As Graphics = e.Graphics
      Dim pn As New Pen(Color.Blue)
      Dim pt1 As New Point(30, 30)
      Dim pt2 As New Point(110, 100)
      g.DrawLine(pn, pt1, pt2)
End sub

它完美无缺,但如果我只想在点击按钮后绘制,例如,

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

      Dim g As Graphics = e.Graphics
      Dim pn As New Pen(Color.Blue)
      Dim pt1 As New Point(30, 30)
      Dim pt2 As New Point(110, 100)
      g.DrawLine(pn, pt1, pt2)

    End Sub

它说''Graphics'不是'System.EventArgs'的成员。???

我也尝试过改变:

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

要:

   Private Sub Button1_Click(ByVal sender As graphics.Object, ByVal e As System.EventArgs) Handles Button1.Click

还有一些类似的变化(很多要列出的),但我得到了很多错误响应。

那么如何使用e.graphics ???

单击按钮绘制一条线

2 个答案:

答案 0 :(得分:0)

您需要对表单的Graphics上下文的引用(我在这里假设WinForms)。

最简单的方法是在按钮点击顶部添加此行:

Dim g As Graphics = Me.CreateGraphics

绘制图形比这更复杂,因为如果OnPaint事件触发,如果你绘制的内容包含在{{1}中,你应该真正地将你绘制的内容保存到内存中并根据需要重新绘制它e.ClipRectangle的属性,但上面的代码行应该让你现在开始。

答案 1 :(得分:0)

您正在使用的两个事件具有不同的EventArgs。 Click EventArgs有关于click和PaintEventArgs的信息,有关要绘制的信息。

您可以调用重绘按钮并使用onPaint方法。这是一种很好的编程风格。将事件与相应的内容配对。油漆涂料。点击点击。

Private drawLine as boolean = false

Private Sub Button1_Paint(sender As Object, e As PaintEventArgs) Handles Button1.Paint
  If drawLine then
    Dim g As Graphics = e.Graphics
    Dim pn As New Pen(Color.Blue)
    Dim pt1 As New Point(30, 30)
    Dim pt2 As New Point(110, 100)
    g.DrawLine(pn, pt1, pt2)
  End if
End sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  drawLine = true
  Button1.refresh()
End Sub