如何在C#中使用OnPaint事件?

Ste*_*ciu 5 c# events onpaint

我在网站上看到了一些类似的问题,但没有一个真正帮助过我.

我有一个函数,当单击一个按钮时,它会在窗体上绘制几行,这些按钮的形状会根据用户在某些文本框中输入的值而变化.

我的问题是,当我最小化形式时,线条消失,我明白这可以通过使用OnPaint事件来解决,但我真的不明白如何.

任何人都可以给我一个简单的例子,使用函数在按下按钮时使用OnPaint事件绘制一些东西吗?

Pav*_*ets 6

在这里,您可以在用户绘制的控件上获得MSDN教程

您必须继承Button类并重写OnPaint方法.

代码示例:

protected override void OnPaint(PaintEventArgs pe)
{
   // Call the OnPaint method of the base class.
   base.OnPaint(pe);

   // Declare and instantiate a new pen.
   System.Drawing.Pen myPen = new System.Drawing.Pen(Color.Aqua);

   // Draw an aqua rectangle in the rectangle represented by the control.
   pe.Graphics.DrawRectangle(myPen, new Rectangle(this.Location, 
      this.Size));
}
Run Code Online (Sandbox Code Playgroud)

编辑:

添加属性到您的类并喜欢public Color MyFancyTextColor {get;set;}并在您的OnPaint方法中使用它.Alsow它将在Visual Studio表单设计器的控件属性编辑器中出现.