当窗体不再需要标签时,从窗体中删除标签

本文关键字:窗体 标签 删除 不再 | 更新日期: 2023-09-27 18:16:23

假设我有一个windows窗体的代码:

public Form1()
{
    this.Shown += new EventHandler(Form1_Shown);
    InitializeComponent();
}
// - This Form1_Shown class is what's done AFTER the form is shown! Put stuff here!
private void Form1_Shown(object sender, System.EventArgs e)
{
    methods.WriteTextToScreen("HelloLabel", "Hello!", 15, 15);
    methods.sleepFor(1);
    methods.EraseScreenLabel(Form1.HelloLabel);
    methods.WriteTextToScreen("GoodbyeLabel", "Goodbye!", 80, 80);
    methods.sleepFor(3);
    methods.EraseScreenLabel(Form.GoodbyeLabel);
}
public class methods
{
    public static int timeSlept;
    public static Label[] UsedTextBoxes = new Label[10000000000000000000];
    public static void WriteTextToScreen(string name, string text, int locX, int locY)
    {
        int numberOfPrintedItems = methods.UsedTextBoxes.GetLength(1);
        Label tempLabel = new Label();
        UsedTextBoxes[numberOfPrintedItems + 1] = tempLabel;
        tempLabel.Text = text;
        tempLabel.Name = name;
        tempLabel.Location = new Point(locX, locY);
        tempLabel.Visible = true;
        tempLabel.Enabled = true;
    }
    public static void EraseScreenLabel(Label label)
    {
        System.Windows.Forms.FlowLayoutPanel obj = new System.Windows.Forms.FlowLayoutPanel();
        obj.Controls.Remove(label);
        label = null;
    }
    public static void sleepFor(int seconds)
    {
        timeSlept = 0;
        System.Timers.Timer newTimer = new System.Timers.Timer();
        newTimer.Interval = 1000;
        newTimer.AutoReset = true;
        newTimer.Elapsed += new System.Timers.ElapsedEventHandler(newTimer_Elapsed);
        newTimer.Start();
        while (timeSlept < seconds)
        {
            Application.DoEvents();
        }
        newTimer.Dispose();
    }
    public static void newTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        timeSlept = IncreaseTimerValues(ref timeSlept);
        Application.DoEvents();
    }
    public static int IncreaseTimerValues(ref int x)
    {
        int returnThis = x + 1;
        return returnThis;
    }

我希望EraseScreenLabel(Label label);方法从屏幕上删除该标签,例如由writeTextToScreen();方法创建的GoodbyeLabel,因为我不想让它再可见。如何让这个方法做我想做的?我已经尝试过使用Dispose();, Finalize();,以及label = null;。有人能提供帮助吗?

当窗体不再需要标签时,从窗体中删除标签

new System.Windows.Forms.FlowLayoutPanel();

你刚刚创建了一个新的空面板。
修改它将不会对表单中的现有面板产生影响。

您需要修改表单上现有的面板。

特别是,你应该摆脱你的methods类,使那些实例方法在表单类。

您还应该将sleepFor()替换为await Task.Delay()