如何在C#中使用OnPaint事件?
我在网站上看到了一些类似的问题,但没有一个真正帮助过我。
我有一个函数,当单击一个按钮时,它会在窗体上绘制几行,这些按钮的形状会根据用户在某些文本框中输入的值而变化。
我的问题是,当我最小化forms时,线条消失,我明白这可以通过使用OnPaint事件来解决,但我真的不明白如何。
任何人都可以给我一个简单的例子,使用函数在按下按钮时使用OnPaint事件绘制一些东西吗?
在这里,您可以在用户绘制的控件上获得MSDN教程
您必须inheritanceButton
类并重写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)); }
编辑:
将属性添加到您的类,并像public Color MyFancyTextColor {get;set;}
,并在OnPaint
方法中使用它。 Alsow它将成为visual studio表单设计师的控件属性编辑器。
您可以编写负责(重新)将场景绘制到Paint
事件发生时调用的方法的所有代码。
因此,您可以注册您在Paint发生时调用的方法,如下所示:
this.Paint += new PaintEventHandler(YourMethod);
然后只要需要重绘表单,就会调用YourMethod。
还要记住,您的方法必须与委托具有相同的参数,在这种情况下:
void YourMethod(object sender, PaintEventArgs pea) { // Draw nice Sun and detailed grass pea.Graphics.DrawLine(/* here you go */); }
编辑
或者,如另一个答案中所述,您可以覆盖OnPaint
方法。 然后,您不必关心使用自己的方法添加事件处理程序。