如何解决一次又一次地使Windows窗体无效
| 我正在使用此代码绘制一些圆,但是它不断重画和重画,并且即使我尝试5或6,也会出现textBox1.text具有错误的数字格式的错误,并且此错误停止了。using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace terc
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void Button1Click(object sender,EventArgs e)
{
this.Paint += new PaintEventHandler(KresliTerc);
}
protected void KresliTerc(object sender,PaintEventArgs e)
{
Graphics grfx = e.Graphics;
int pocet = int.Parse(textBox1.Text);
label1.Text = pocet.ToString();
for(int i=1; i <= pocet; i++)
{
grfx.FillEllipse(Brushes.Black,ClientSize.Width/2,ClientSize.Height/2,50*i,50*i);
Invalidate();
}
}
}
}
解决方法
this.Paint += new PaintEventHandler(KresliTerc);
您在哪里调用此函数,因为它是绘画事件,所以在绘画时会一次又一次地调用
,为什么每次单击按钮时都附加事件处理程序?这意味着您将拥有与按钮单击一样多的事件处理程序,我怀疑这是您想要的。
但是,您的重画问题可能是您在Paint事件处理程序中调用Invalidate
的事实。这将强制重新绘制该窗体。因此,对于每次绘制,您将触发一个新的绘制,这将触发一个新的绘制,依此类推。
,您不应使Paint调用无效。
根据一些整数或布尔值处理绘画。
在点击事件中设置整数或布尔值,然后在按钮点击处理程序中调用Invalidate。
, Boolean isButtonClicked;
protected override void OnPaint(PaintEventArgs e)
{
if (this.isButtonClicked)
{
this.isButtonClicked = false;
// some paint logic goes down here...
e.Graphics.FillEllipse(Brushes.YellowGreen,12,54,54);
}
}
private void HandleOnButtonClick(Object sender,EventArgs e)
{
this.isButtonClicked = true;
this.Invalidate();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。