どうもWEBに出ていたコードに疑問が残るので、「いらないんじゃないか?」と思われるコードを整理してみました。そうしたらやっぱり動きました。

 

【習作C#プログラム】

// paintargs01.cs

using System;
using System.Drawing;
using System.Windows.Forms;

class paintargs01
{
    public static void Main()
    {
        Form f = new Form();
        f.Text = "猫でもわかるプログラミング";
        f.BackColor = Color.White;
        f.Paint += new PaintEventHandler(MyHandler);
        Application.Run(f);
    }

    static void MyHandler(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.DrawLine(new Pen(Color.Red), 10, 50, 280, 50);
    }
}
 

【再修正したVBプログラム】

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

Class paintargs01

 

    'Visual Basicの場合、PaintEventHandlerとしてイベントを宣言する
    ’Public Event Paint As PaintEventHandler→どう考えてもこれはいらないよね。
 

    Public Shared Sub Main()
        Dim f As Form = New Form()
        f.Text = "猫でもわかるプログラミング"
        f.BackColor = Color.White
        'f.Paint += New PaintEventHandler(AddressOf MyHandler)
        'C#の↑に相当するコードが以下3行となる
        'Dim PEH As PaintEventHandler
        'PEH = AddressOf MyHandler
        'AddHandler f.Paint, PEH
        'https://learn.microsoft.com/ja-jp/dotnet/visual-basic/language-reference/statements/addhandler-statement
        ’↓こう書けばよいだけじゃない?

        AddHandler f.Paint, AddressOf MyHandler
        Application.Run(f)
    End Sub

    Private Shared Sub MyHandler(ByVal sender As Object, ByVal e As PaintEventArgs)
        Dim g As Graphics = e.Graphics
        g.DrawLine(New Pen(Color.Red), 10, 50, 280, 50)
    End Sub
End Class

 

これでやっとコンバートしたっていう感じになりました。が、なんだか、今日一日すっごく疲れた。