c#中如何实现点击按钮后在picturebox中绘图

点击button后,会有一条直线绘制在picturebox中,该怎么写事件呢?
private void button1_Click(object sender, EventArgs e)
{
Graphics g = pictureBox1.CreateGraphics;
Pen p = new Pen(Color.Red, 2);
g.DrawLine(p, 0, 0, 100, 100);
}
这样写似乎不行呃,求大神指教

需要对PictureBox的Pain事件编程

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        bool b = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            b = true;
            pictureBox1.Refresh();
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (b == false) return;
            Graphics g = e.Graphics;
            Pen p = new Pen(Color.Red, 2);
            g.DrawLine(p, 0, 0, 100, 100);
        }
        
    }
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-01-27

看你要画什么了,简单的矩形如下:

        private void button1_Click(object sender, EventArgs e)
        {
            Graphics g = this.pictureBox1.CreateGraphics();
            g.DrawRectangle(new Pen(Color.Red), 0, 0, 100, 100);
        }

第2个回答  2015-11-05
在窗体上设置一个按钮和一个picturebox,代码里在按钮的点击事件里写绘图函数或过程
相似回答