プロが教えるわが家の防犯対策術!

C#を勉強しているのですが、GUIを作り初めて描画処理で分からない所があり、質問させて頂きます。
基本クラスの方で「Hello, world!」という文字列をDrawStringで表示させる事は出来たのですが、それを基本クラスを継承した派生クラスのメソッドで行うと何も表示されないんです。
以下が試したコードです。

//基本クラスSample1
using System;
using System.Drawing;
using System.Windows.Forms;

public class Sample1 : Form
{
  protected Bitmap image;
protected Graphics g;

protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);

Sample2 s = new Sample2();

s.helloworld();
e.Graphics.DrawImage(image, 0, 0);
}

public Sample1()
{
SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);

image = new Bitmap(600, 400);
g = Graphics.FromImage(image);
}

static void Main()
{
Form form = new Sample1();
form.Text = "sample";
form.ClientSize = new Size(600, 400);
form.BackColor = Color.FromArgb(0xff, 0xff, 0xff);
Application.Run(form);
}
}

//派生クラスSample2
using System;
using System.Drawing;
using System.Windows.Forms;

public class Sample2 : Sample1
{
Brush brush = new SolidBrush(Color.Black);

public void helloworld()
{
g.DrawString("Hello, world!", this.Font, brush, 10, 10);
}
}

なぜ表示されないのか分かる方いらしたら、ご教授願えないでしょうか。是非お願いします。

A 回答 (1件)

DrawImageで描画しようとしているのが 何も描画されていない Sample1.Imageだからだと思います



Sample2 s = new Sample2();
s.helloworld();
で描画されてるのは s.image であり呼び出し元のForm.imageに描画されるわけではありません

OnPaintの中を

base.OnPaint(e);

Sample2 s = new Sample2();

s.helloworld();
// this.imageでは無く s.imageを描画
e.Graphics.DrawImage(s.image, 0, 0);
といった具合に変更しましょう
    • good
    • 0
この回答へのお礼

回答有難う御座います。
言われた通り書き直しまして、見事表示させる事ができました。本当に有難う御座いました。

お礼日時:2009/01/19 01:06

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!