Search code examples
c#eventsmethodstimer

How do i fire an event after a few seconds?


I am making a application where i would like to log in with a face detection. But this is not real, its just to make ik look like its scanning. So when i press the LOG IN button, the kinect takes my picture and show me the picture, on top of it is showing me in a text that its scanning. Now i am stuck with the following issue, when i press the login button, the scanning label appears, but i would like to fire an other event that takes me to the next page, the homepage. So i want the SCANNING label appearing for 3 seconds, and then the page should change. This is what i tried, i worked with a timer, but that doesnt do annything.

    private void ActionButton_Click(object sender, System.EventArgs eventArgs)
    {

        _main.TakePicture();
        identifyBox.Source = _main.source.Clone();
        scanningLabel.Visibility = Visibility.Visible;
        _storyboard = (Storyboard)FindResource("scanningSB");
        //_storyboard.Begin();
        Start();
    }

    private void Start()
    {
        _tm = new Timer(3000);
        _tm.Elapsed += new ElapsedEventHandler(_tm_Elapsed);
        _tm.Enabled = true;
    }

    void _tm_Elapsed(object sender, ElapsedEventArgs e)
    {
        if (_tm == new Timer(3000))
        {
             ((Timer)sender).Enabled = false; 
            _main.ContentPage.Children.Clear();
            _main.ContentPage.Children.Add(_homeScreen);
        }
    }

Okay i removed the if statement, but now it fires every 3 seconds a method. How can i make it work 1 time.

Ok even this works, now i my ContentPage wont change? It gives me this error: The calling thread cannot access this object because a different thread owns it. What can be wrong?


Solution

  • I think you can remove condition

    if (_tm == new Timer(3000))
    

    and keep it simple

    void _tm_Elapsed(object sender, ElapsedEventArgs e)
    {
    
        ((Timer)sender).Enabled = false; 
    
        _main.ContentPage.Children.Clear();
        _main.ContentPage.Children.Add(_homeScreen);
    
    }
    

    when you set _tm = new Timer(3000); it will set the time to fire event after 3 seconds..