简体   繁体   English

如何通过单击按钮更改线条的颜色?

[英]How to change colour of a line with click of a button?

I am able to change colour of a line,like this:-我可以像这样改变线条的颜色:-

Pen P1 = new Pen(Color.Blue, 3);
PointF pt1 = new PointF(450.0F, 60.0F);
PointF pt2 = new PointF(20.0F, 60.0F);
e.Graphics.DrawLine(P1, pt1, pt2);

But, I am not able to change the colour of a line with a button's click.但是,我无法通过单击按钮来更改线条的颜色。

Please tell how to change the colour of a line with click of a button, in windows form, visual studio, in c#.请告诉如何通过单击按钮更改线条的颜色,在 windows 表格中,visual studio,在 c# 中。

Create a field of type Pen and initialize its Color to color you want and in Button 's Click event handler, change the color of the pen and Invalidate the client area of the Form to trigger a paint event.创建一个Pen类型的字段并将其Color初始化为您想要的颜色,然后在ButtonClick事件处理程序中,更改笔的颜色并使Form的客户区Invalidate以触发绘制事件。

public partial class Form1: Form
{
    public Form1()
    {
        SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
        InitializeComponent();
        m_pen = new Pen(Color.Black, 2.0f);
    }
    private Pen m_pen = null;
    
    protected override void OnPaint(PaintEventArgs e)
    {
         base.OnPaint(e);
         e.Graphics.DrawLine(m_pen, 0, 0, 100, 100);
    }
    private void button1_Click(object sender, EventArgs e)
    {
         m_pen.Color = Color.Blue;
         Invalidate(); 
    }
 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM