Search code examples
c#datetimetimeofday

Logging into form at different times of day does different events


In my c# windows form application I have a webBrowser and a lot of buttons and 2 timers and other stuff. My form logs me into my college website and I have multiple classes throughout the week, my form has a clock in it and buttons that I click to go to each of my college subjects. I want to give my form someway of knowing what time it is and execute the corresponding college class button for that time of day. So for example if I start my form on Monday at 9am it logs me in it executes the button1.PerformClick(); , which takes me to OHS and say if I start my form on Tuesday at say 1pm it logs me in and clicks button2.PerformClick();, which takes me to a different subject and so on. My form clock works perfect and my login works perfect, and my buttons that go to my college classes work but now I want to automate it. By running the form which I have made it auto login but how now can I make my form know what time and day it is and button.performClick for the button I need on that day?I'm not sure even what to search for or if its even possible please answer.


Solution

  • Well, there are a couple of ways of getting this done. Since you want this to be done at application startup, I'd do something like this:

    var now = DateTime.Now;
    if (now.DayOfWeek == DayOfWeek.Monday)
    {
        if (now.Hour >= 9 && now.Hour <= 12)
        {
             LoadOhsPage();
        }
        else if (now.Hour > 12 && now.Hour <= 16)
        {
            LoadSomeOtherPage();
        }
        // ...and so on...
    }
    else if (now.DayOfWeek == DayOfWeek.Tuesday)
    {
         // ...similar to above...
    }
    // ...and so on...
    

    You could do the whole Timer automation like Psychemaster suggested, but that would automate things while you're using the program, and I don't think you want it to try and load a different page while you're working on something. Alternatively, you could implement that Timer, but also include a notification somewhere on the page, telling you that it's time for another class, so that you may click on it when you're done with your current task. If you decide to go that route, Timer automation is beyond simple and you can find out more at MSDN (scroll to the bottom for an example).

    Just in case that link is broken, here's a quick sample code:

    var appTimer = new Timer();
    
    appTimer.Interval = 3600000; // 1 hour, alternatively 1800000 would be 30 minutes.
    appTimer.Tick += new EventHandler(CheckDateTime);
    appTimer.Start();
    
    private void CheckDateTime(Object obj, EventArgs args)
    {
        // Similarly to the first code, check the day of the week and the hour of the day;
        // then perform an appropriate action, such as notifying the user that it's time
        // to work on something else.  This is a better approach than forcing them to change
        // pages.
    }