Update function to update date and time?

Asked

Viewed 1,144 times

2

I have a Windows Form, on the control bar (where you have the Title, close and minimize) I also have the date and time:

        this.hora.Text = DateTime.Now.ToShortTimeString();
        this.data.Text = DateTime.Now.ToShortDateString();

But it is not updating alone, I tried to do taking the movement of the mouse and pressed key, but can not call the functions that perform this all the time.. I don’t know, I have no idea how to do it, I had only seen C# in Unity and there was the function ready Update who played this role (kept updating and executing the commands within it), but how do I do this in Visual?

I’m calling it that:

 public Interface()
    {
        InitializeComponent();
        KeyPress += _keyPress;
        MouseMove += _mouseMove;

    }
    public void _mouseMove(object sender, MouseEventArgs e)
    {
        this.mouseLocation = e.Location;
        this.hora.Text = DateTime.Now.ToShortTimeString();
        this.data.Text = DateTime.Now.ToShortDateString();
    }
    public void _keyPress(object sender, KeyPressEventArgs e)
    {
        this.hora.Text = DateTime.Now.ToShortTimeString();
        this.data.Text = DateTime.Now.ToShortDateString();
    }
  • This Form is what? WPF, XAML?

  • Windows Form, . Cs even

  • When do you call both lines? At which Form event?

  • I put there in the post.. these functions are to capture pressed key or busy mouse

  • They are called there at the beginning when I put them in the operation

  • 3

    You need to insert a Timer in the form, and at the event tick timer put your code. Set the timer interval property to 1000 (milliseconds). I think the event calls tick, but double-clicking the timer is the event that the visual studio automatically creates.

  • 1

    The timer serves exactly for this, it calls the event every N milliseconds.

  • It worked perfectly, I didn’t know what Timer was doing well, thanks for the explanation, helped me even in another thing I was trying to do! Vlw

  • event is nameTimer_Tick itself

Show 4 more comments

2 answers

0

You need to Use a Timer to be able to update the date and/or time in a given time range at your discretion.
Behold Here Maneiras!)

0


First, declare that timer:

 public Timer WithEventsnowUpdater = new Timer();

Now put this method:

 public override void OnLoad() {
      nowUpdater.Enabled = true;
      nowUpdater.Interval = 1000; /*1 segundo = 1.000*/
      nowUpdater.Tick += onLoad();
 } //ou coloque essas duas linhas no método Form1_Load()

 public void nowTick() {
      this.hora.Text = DateTime.Now.ToShortTimeString();
      this.data.Text = DateTime.Now.ToShortDateString();
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.