ヘッダー
Visual Basic サンプル集
VB2005対応 VB2008対応 VB2010対応 VB2012対応 VB2013対応 VB2015対応 VB2017対応 VB2019対応

ボタンをクリックしたら図形を描画する

2020/12/20

→ C# のサンプルに切り替える

 

このページで紹介するサンプルは Windowsフォームアプリケーションを前提にしています。

 

ボタンをクリックしたら、赤い線を描画する

実行するにはフォームにボタンを1つ(Button1)とPictureBoxを1つ(PictureBox1)を配置します。

VB2005対応 VB2008対応 VB2010対応 VB2012対応 VB2013対応 VB2015対応 VB2017対応 VB2019対応

Public Class Form1

    Dim isDraw As Boolean = False

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

        isDraw = True
        PictureBox1.Invalidate()

    End Sub

    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint

        If Not isDraw Then
            Return
        End If

        Dim point1 As New Point(10, 20)
        Dim point2 As New Point(200, 150)

        e.Graphics.DrawLine(Pens.Red, point1, point2)
    End Sub

End Class

メモ:描画時点で描画内容が決まっている場合、この例が便利です。お絵かきアプリのように描画後に描画内容が追加・変更される可能性がある場合、次の例の方が便利です。

 

 

Button1をクリックすると四角を追加し、Button2をクリックすると円を追加する

実行するにはフォームにボタンを2つ(Button1, Button2)とPictureBoxを1つ(PictureBox1)を配置します。

ボタンはどちらを先にクリックしてもOKです。両方クリックすると四角と円の両方が描画されます。

VB2005対応 VB2008対応 VB2010対応 VB2012対応 VB2013対応 VB2015対応 VB2017対応 VB2019対応

Public Class Form1

    Dim paths As New List(Of Drawing2D.GraphicsPath)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim path As New Drawing2D.GraphicsPath
        path.AddEllipse(10, 20, 200, 150)
        paths.Add(path)
        PictureBox1.Invalidate()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim path As New Drawing2D.GraphicsPath
        path.AddRectangle(New Rectangle(10, 20, 200, 150))
        paths.Add(path)
        PictureBox1.Invalidate()
    End Sub

    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint

        For Each path As Drawing2D.GraphicsPath In paths
            e.Graphics.DrawPath(Pens.Red, path)
        Next

    End Sub

End Class

メモ:お絵かきアプリのように描画後に描画内容が追加・変更される可能性がある場合、この例が便利です。描画時点で描画内容が決まっている場合、前の例の方が便利です。

 

 

ボタンをクリックすると四角形が右に移動する

実行するにはフォームにボタンを1つ(Button1)とPictureBoxを1つ(PictureBox1)を配置します。

VB2005対応 VB2008対応 VB2010対応 VB2012対応 VB2013対応 VB2015対応 VB2017対応 VB2019対応

Public Class Form1

    Dim x As Integer

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        x += 2
        PictureBox1.Invalidate()
    End Sub

    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint

        e.Graphics.DrawRectangle(Pens.Red, x, 20, 200, 150)
        
    End Sub

End Class

 


VB6対応 VB6ではPaintイベントではなく、ボタンのClickイベントで直接Lineなどの描画命令を実行します。