标记内容和进度条

本文关键字: | 更新日期: 2023-09-27 18:13:47

我创建了windows表单应用程序,并添加了进度条来显示加载文件的进度,并在进度条上方添加标签来显示每个文件的路径,但总和路径很长,并且显示在一行中,但我的宽度表单很小,因为有些路径没有全部显示,我在堆栈溢出和谷歌中看到了多个解决方案,并更改大小。我要方法动态改变路径的长度。

标记内容和进度条

要显示整个路径(例如,换行(,您需要将LabelHeight设置为某个值,比如50。所以它可能有点像LabelHeight50Width300,然后是下面的ProgressBar

此外,您的问题似乎是在主线程上执行长时间运行的操作。这就是为什么Label不令人耳目一新的原因。您需要利用BackgroundWorker。所以,为它添加一个类变量:

private BackgroundWorker _worker = new BackgroundWorker();

然后在ctor中执行以下操作:

_worker.WorkerReportsProgress = true;
_worker.DoWork += DoBackgroundWork;
_worker.ProgressChanged += ReportProgress;

然后对于那些处理程序:

private void DoBackgroundWork(object sender, DoWorkEventArgs e)
{
    // do the work you're doing in here -but add the below line when you want
    // to update the text of your label
    _worker.ReportProgress(1, "Your label text here");
}
private void ReportProgress(object sender, ProgressChangedEventArgs e)
{
    this.label.Text = e.UserState as string;
}

您可能需要考虑的最后一件事是,将字符串剪切到标签长度的附近,而不是试图使其包裹。以下是一组方法,证明了一个可能的解决方案。

需要注意的一件事是,截断过程利用了bin搜索,因此它不是令人难以置信的准确。我的意思是什么?假设你有一个150个字符长的字符串(就像下面例子中的那个(,第一次它把它切成两半并测量字符串。如果该宽度小于最大宽度(例如Label的宽度(,它只会返回该字符串。这是可行的,但标签的长度可能还有空间,因此可能会截断更少的字符。

为了更准确,你必须进行更多的传球,而IMO,这还不足以进行可枚举的传球。

public partial class Form1 : Form
{
    string[] chars = new string[]
    {
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
    };
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        var filePath = BuildString(150);
        var g = this.label1.CreateGraphics();
        var size = g.MeasureString(filePath, this.Font);
        var oneCharacterLen = (size.Width / (float)filePath.Length);
        if (size.Width > ((float)this.label1.Width - (oneCharacterLen * 3f)))
        {
            this.label1.Text = CutoffStringBinSearch(g, string.Format("{0}", filePath), 0, this.label1.Width);
        }
    }
    private string CutoffStringBinSearch(Graphics g, string s, int startIndex, int maxWidth)
    {
        var midPoint = (s.Length - startIndex) / 2;
        var subString = string.Format("{0}...", s.Substring(startIndex, midPoint));
        var len = g.MeasureString(subString, this.Font);
        if (len.Width > (float)maxWidth) { return CutoffStringBinSearch(g, s.Substring(startIndex, midPoint), 0, maxWidth); }
        return subString;
    }
    private string BuildString(int len)
    {
        string[] s = new string[len];
        var random = new Random(0);
        for (int i = 0; i < len; i++)
        {
            s[i] = chars[random.Next(0, chars.Length - 1)];
        }
        return string.Join("", s);
    }
}
using System;

使用System.ComponentModel;使用System.Windows.Forms;

命名空间BackgroundWorkerSimple{公共分部类Form1:Form{公共窗体1(({InitializeComponent((;backgroundWorker1.WorkerReportsProgress=true;backgroundWorker1.WorkerSupportsCancelation=true;}

    private void startAsyncButton_Click(object sender, EventArgs e)
    {
        if (backgroundWorker1.IsBusy != true)
        {
            // Start the asynchronous operation.
            backgroundWorker1.RunWorkerAsync();
        }
    }
    private void cancelAsyncButton_Click(object sender, EventArgs e)
    {
        if (backgroundWorker1.WorkerSupportsCancellation == true)
        {
            // Cancel the asynchronous operation.
            backgroundWorker1.CancelAsync();
        }
    }
    // This event handler is where the time-consuming work is done. 
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        for (int i = 1; i <= 10; i++)
        {
            if (worker.CancellationPending == true)
            {
                e.Cancel = true;
                break;
            }
            else
            {
                // Perform a time consuming operation and report progress.
                System.Threading.Thread.Sleep(500);
                worker.ReportProgress(i * 10);
            }
        }
    }
    // This event handler updates the progress. 
    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
    }
    // This event handler deals with the results of the background operation. 
    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled == true)
        {
            resultLabel.Text = "Canceled!";
        }
        else if (e.Error != null)
        {
            resultLabel.Text = "Error: " + e.Error.Message;
        }
        else
        {
            resultLabel.Text = "Done!";
        }
    }
}

}

使用labelX.Refresh((.

label1.Text = "First text";
Thread.Sleep(1500); //*This line is only for testing purpose as the change is pretty quick*. 
progressBar1.Value = 50;
label1.Refresh();
label1.Text = "Second text";
Thread.Sleep(1500); //*This line is only for testing purpose as the change is pretty quick*. 
label1.Refresh();
相关文章:
  • 没有找到相关文章