标签中的大字符串导致应用程序挂起(c# Windows)

本文关键字:挂起 Windows 应用程序 字符串 标签 | 更新日期: 2023-09-27 18:13:13

我有一个windows应用程序,我从数据库中获取数据并将其绑定到标签。我使用定时器和滚动标签,这工作很好,当字符串是大约150个字符,但当我有大约30000个字符的字符串,它只是挂出应用程序。

       lblMsg1.AutoEllipsis = true;
  private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (lblMsg1.Right <= 0)
                {
                    lblMsg1.Left = this.Width;
                }
                else
                    lblMsg1.Left = lblMsg1.Left - 5;
                this.Refresh();
            }
            catch (Exception ex)
            {
            }
        }
public void bindData()
{
lblMsg.Text = "Some Large text";
}
 public void Start()
        {
            try
            {
                timer1.Interval = 150;
                timer1.Start();
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
        }

为什么这与字符串长度有关并导致应用程序挂起?

标签中的大字符串导致应用程序挂起(c# Windows)

我猜你正在尝试创建一个新闻提要?我不确定标签的设计是为了容纳这么大的字符串。请使用图片框,并更新您的代码。

在表单类中定义两个变量。一个用于保存文本偏移量,另一个用于保存图片框的图形对象。这样的:
private float textoffset = 0;
System.Drawing.Graphics graphics = null;

在onload表单中这样做:

private void Form1_Load(object sender, EventArgs e)
{
    textoffset = (float)pictureBox1.Width; // Text starts off the right edge of the window
    pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    graphics = Graphics.FromImage(pictureBox1.Image);
}

你的计时器应该是这样的:

private void timer1_Tick(object sender, EventArgs e)
{
    graphics.Clear(BackColor);
    graphics.DrawString(newstickertext, new Font(FontFamily.GenericMonospace, 10, FontStyle.Regular), new SolidBrush(Color.Black), new PointF(textoffset, 0));
    pictureBox1.Refresh();
    textoffset = textoffset-5;
}

使用文本框代替标签,并根据需要设置滚动条、多行和换行属性。要禁用编辑TextBox(从而使其行为类似于标签),请使用ReadOnly属性。