使用委托绘制形状

时间:2019-02-21 19:31:08

标签: c# winforms events delegates

我的任务-创建自己的委托和事件。 Count对数量进行计数,当事件发生时,在Form1上绘制一个矩形。没有错误发生,但没有绘制矩形。在Rect类中绘制矩形的方法。我不知道为什么吗? Count.cs

public delegate void MyDel(object sender, MyEventArgs e);    
public class MyEventArgs
{
    public Graphics G { get; set; }
    public MyEventArgs(Graphics g) { G = g; }
}
class Count
{
    Graphics g;        
    public event MyDel DrawIt;
    public int N { get; set; }
    public Count(int n) { N = n; }
    public void CountIt(int N)
    {
        int a = 0;
        for (int i = 0; i < N; i++)
        {
            a += i;
            if (a > 10)
               OnCount();
        }
    }
    public void OnCount()
    {
        MyDel handler = DrawIt;
        if (handler != null)
            handler(this, new MyEventArgs(g));
    }
}

Rect.cs

class Rect
{...        
    public void DrawRect(Graphics g){g.DrawRectangle(P, X, Y, Width, Height);}
}

Form1.cs

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Graphics g = this.CreateGraphics();
        Count c = new Count(10);
        Rect r = new Rect(new Pen(Color.Red, 5), 50, 50, 100, 100);
        c.DrawIt += (s, e) => { r.DrawRect(g); };            
    }        
}

谢谢。

0 个答案:

没有答案