Search code examples
c#formshideswitching

open last active form C#


Hi i am relatively new to C# and am creating a troubleshooting training guide for new starters so will be creating many forms. i am currently using a simple open new form and hide current code which is working well until now. on each form i have a next and previous link label. the problem i have run into now is that i have two forms that lead to the same form and the code i am using will only go to one.

this is what i am using:

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
  Home myNewForm = new Home();
  myNewForm.Visible = true;

  this.Hide();
}

so my question is how can i switch from the current form back to the last active form rather then a set form as in the code above?


Solution

  • NOTE

    This code wasn't tested - may contain some typos

    I would create an interface for it but to make it simplier - create a class which can extend the form with additional DateTime property(it could also be some kind of boolean). Like below:

    public class FormExtended{
        public Form _form{get;set;}
        public DateTime lastActive {get;set;}
        ...
    }
    

    Later on for each form create an instance of this class. For example:

    public FormExtended CreateNewForm()
    {
        var extension = new FormExtended();
        extension._form = new YourForm();
        extension.lastActive = DateTime.Now;
        listOfForms.Add(extension); //listOfForms - some kind of global list to hold all instances
        return extension;
    
        //if you want to You can make it void and just show the form without return
        //extension._form.Show();
    
    }
    

    Now in calling method you can find latest active with linq and showit:

    public void showLastActiveForm()
    {
        var latestForm = listOfForms.OrderByDescending(x => x.lastActive).Take(1);
        latestForm._form.Show();
    }