How to call a Paint method from a Click event?

时间:2016-09-01 19:23:13

标签: c# winforms visual-studio-2013

The issue I am having is, I cannot get the "e.Graphics" lines of code to work if I try to use them in a button1_Click method. So, I have constructed "Paint" method. Now I can't seem to call the Paint method from the button Click event. Is there a way to do this? I have not been able to find a way to make this work. Or, is there a way to do the e.Graphics functions in the "button1_Click" method?

Thank you

    public void button1_Click(object sender, EventArgs e)
    {
        CrochetPtrnDesign_Paint(this, ?);
    }

    private void CrochetPtrnDesign_Paint(object sender, PaintEventArgs e)
    {
        Rectangle rect = new Rectangle(5, 5,
            ClientSize.Width - 10, ClientSize.Height - 10);
        e.Graphics.DrawRectangle(Pens.Red, rect);

        using (Font font = new Font("Times New Roman", 16, GraphicsUnit.Pixel))
        {
            using (StringFormat sf = new StringFormat())
            {
                // Middle.
                sf.LineAlignment = StringAlignment.Center;  // Middle.

                // Middle/Center.
                sf.Alignment = StringAlignment.Center;      // Center.
                e.Graphics.DrawString("Middle/Center", font, Brushes.Black, rect, sf);
            }
        }

2 个答案:

答案 0 :(得分:5)

  

如果我尝试在button1_Click方法中使用它们,我无法使“e.Graphics”代码行工作

这是设计的。在处理Click事件时,您不应该绘制任何内容。所以调用Paint事件处理程序至少是不方便的。

执行此操作的正确方法是在处理Invalidate()时调用Click,然后让Windows决定何时调用您的Paint事件处理程序。如果由于Click事件而应该以不同方式绘制某些内容,那么Click事件处理程序应该更新您的数据以指示这一点,以便稍后调用Paint事件处理程序时,它确切地知道当时要画什么。

答案 1 :(得分:4)

案例一:绘制到Controls

如果Paint事件实际上是连接,而不仅仅是您复制的一段代码,这将完成这项工作:

public void button1_Click(object sender, EventArgs e)
{
    CrochetPtrnDesign.Invalidate();
}

更新:因为我们现在知道CrochetPtrnDesignForm,只需写下:this.Invalidate();

如果对hooking up read this有疑问!

请注意,只能由系统创建真正有效的PaintEventArgs ..

案例二:绘制到位图:

要绘制到Bitmap,您还需要一个有效的Graphics对象,但您必须自己创建它:

void DrawStuff(Bitmap bmp)
{
    using (Graphics g = Graphics.FromImage(bmp))
    {
        // draw your stuff
        g.DrawRectangle(...);
    }
    // when done maybe assign it back into a Control..
    pictureBox.Image = bmp;
}

<强>更新

将位图分配给pictureBox.Image将起作用,但存在泄漏上一张图像的风险。为避免这种情况,您可以使用一种易于安全的方法,可能是这样的:

void SetImage(PictureBox pb, Bitmap bmp)
{
    if (pb.Image != null)
    {
        Bitmap tmp = (Bitmap)pb.Image;
        pb.Image = null;
        tmp.Dispose();
    }
    pb.Image = bmp;

}