在不再需要时从Windows窗体中删除标签

时间:2013-06-02 13:19:46

标签: c# forms labels

说我有一个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);方法从屏幕上删除该标签,例如GoodbyeLabel方法创建的writeTextToScreen();,因为我不希望它再次可见。我怎样才能让那个方法做我想要的呢?我已尝试使用Dispose();Finalize();以及label = null;。任何人都可以提供任何帮助吗?

1 个答案:

答案 0 :(得分:1)

new System.Windows.Forms.FlowLayoutPanel();

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

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

特别是,您应该删除methods类并在表单类上创建这些实例方法。

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