0

I would like to create "rolling numbers" on a windows form for about 10 seconds.

I've tried with loops but i got problems with refresh (the forms freezes and updates when the loop is done) updating a text label.

It would be nice when it looks like this https://youtu.be/Q7JmiCAAqu0 (made on console)

Sorry for bad english ^^

  • Welcome to Stackoverflow. Please take a tour of the help center- https://stackoverflow.com/help/ – Souvik Ghosh Dec 28 '17 at 13:36
  • 3
    Doing a simple loop on the UI thread will freeze the whole program until it ends. Try moving the "loop" code to a `BackgroundWorker` or use `async`/`await` to run the code on a background thread. – Alejandro Dec 28 '17 at 13:36
  • Use a System.Windows.Forms.Timer, Every X tick you call a function that refresh your UI with the next number. Draging a time from the toolbox would be a simple solution too. [related](https://stackoverflow.com/questions/6169288/execute-specified-function-every-x-seconds) – Drag and Drop Dec 28 '17 at 13:40

1 Answers1

1

Drag one Label on your Form and one Timer. Insert the following code after 'InitializeComponent();

        const int maximum = 100;
        int actual = 0;
        timer1.Interval = 100;
        timer1.Enabled = true;
        timer1.Tick += (sender, args) =>
        {
            label1.Text = (actual++ % maximum).ToString();
        };

Explanation:

  • Label is used to show the rolling numbers
  • Timer is used to perform an operation every N miliseconds (in our case every 100ms = 0.1s)
  • const int maximum = 100; // defines the maximum number we want to show
  • int actual = 0; // represents the actual number we are showing at a time
  • timer1.Interval = 100; // interval after which the timer1.Tick is called (in our case 100ms)
  • timer1.Enabled = true; // enables the timer, without it the Tick would not get called
  • timer1.Tick += (sender, args) => { label1.Text = (actual++ % maximum).ToString(); // set the text to: actual + 1 modulo 100 };

EDIT: Information about modulo: https://en.wikipedia.org/wiki/Modulo_operation

Norbert Szenasi
  • 993
  • 10
  • 24