Bits & Bytes

Posts Tagged ‘console’

Creating Timer Events in C#

If you want something to happen in a C# program at regular time intervals, the ideal way is to create a callback function that makes use of the Timer class. Below, I have created a class called CTimedObject that holds a Timer object. In the constructor, the Timer is allocated with a time interval of 2000 milliseconds or 2 seconds. Then OnTimedEvent() is set as a callback using the += operator and the Elapsed property. Finally, The Timer is started via a call to Start().

At this point, OnTimedEvent() will be called every 2 seconds. Inside the OnTimedEvent() function, the time is written to the console window via the passed in event object of type ElapsedEventArgs. The Object that is passed in is the Timer. Executing the program, the output looks like this

TimerEvent

Program.cs

using System;
using System.Timers;

namespace UsingTimers {
    class Program {
        static void Main(string[] args) {
            CTimedObject qTimedObject = new CTimedObject();
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
        }
    }
}

CTimedObject.cs

using System;
using System.Timers;

namespace UsingTimers {
    class Program {
        static void Main(string[] args) {
            Timer qTimer = new Timer(2000);
            qTimer.Elapsed += OnTimedEvent;
            qTimer.Start();
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
        }

        static private void OnTimedEvent(Object qTimer, ElapsedEventArgs eElapsed) {
            Console.WriteLine(eElapsed.SignalTime);
        }
    }
}

The code above demonstrates how to use a Timer in an object. Alternatively, we could do the same thing more simply if we just want the event to fire with a static function. Below, we have code that does exacly the same thing without using a separate class.

Program.cs

using System;
using System.Timers;

namespace UsingTimers {
    public class CTimedObject {

        Timer mqTimer = null;

        public CTimedObject() {
            mqTimer = new Timer(2000);
            mqTimer.Elapsed += OnTimedEvent;
            mqTimer.Start();
        }

        private void OnTimedEvent(Object qTimer, ElapsedEventArgs eElapsed) {
            Console.WriteLine(eElapsed.SignalTime);
        }
    }
}

Printing Messages to the Console Window in C#

This is one of the most fundamental elements of C# programming. In a simple console application, we often want to output some value or set of values to the console window where we can see them. To do this, we can call the functions Console.Write() and Console.WriteLine(). Both of these functions can be use with all of the primitive data types, including strings. The main difference between the functions is that the second one puts an endline or linefeed/carriage return at the end of the output to set the future output to the next line.

To demonstrate, we have a simple program below that prints the closing prices on a given day for two company stock symbols: MSFT and RSH. These two symbols, MSFT and RSH, are the ticker symbols for the companies Microsoft and Radio Shack. This is a simple Console Application project. All of the code outside of the Main() function is standard, boilerplate code that is generated by the Visual Studio IDE. So, we will ignore that and talk about the output statements inside the Main() function.

Inside the Main() function, I start with four lines that output message “Closing Prices – Date: 8/21/2014” with a line underneath it. Notice that I used the Console.Write() function for the first two print statements so that all of the text from the first three statements was printed on one line. The next call to Console.WriteLiine() adds the endline to separate the output for the next line of dashes. The line of dashes is written with the Console.Write() function. However, I added the “\u000D\u000A” at the end which is the equivalent of a linefeed/carriage return or endline character. This makes the call the equivalent of a call to Console.WriteLine(). It is useful to know this, since this can be used anywhere inside of a string to create an endline.

In the last four lines, I output the symbols for Microsoft and Radio Shack along with their respective closing prices for the day. To do this, I created decimal type variables and assigned them values. The decimal data type requires that I put an “M” suffix at the end of each number so that the compiler interprets it as a decimal type. Then I call Console.WriteLine() twice for each string that is passed in. The first string is created automatically from the string literal, “MSFT: ” concatenated with the decimal value contained in dMsftPrice via the “+” operator. The final output look like this:

ConsoleOutput

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyConsoleApplication {
    class Program {
        static void Main(string[] args) {
            Console.Write("Closing Prices - ");
            Console.Write("Date: ");
            Console.WriteLine(new DateTime(2014, 8, 21).ToShortDateString());
            Console.Write("-----------------------------------\u000D\u000A");

            decimal dMsftPrice = 45.22M;
            Console.WriteLine("MSFT: " + dMsftPrice);
            decimal dRshPrice = .67M;
            Console.WriteLine("RSH:   " + dRshPrice);
        }
    }
}

Keeping the C++ Console Window Open

One of the first problems that new C++ programmers have is keeping the console window open when writing C++ programs. The easiest solution to this problem is to use the Start Without Debugging option under the Debug the when executing programs. Unfortunately, Microsoft took this option and many others out of the default menus in Visual C++ 2010. To get this option back, select Tools->Settings->Expert Settings. Otherwise, you can use press (Ctrl + F5) to select Start Without Debugging without the menu.

That’s the simplest option for keeping the console window open. However, if you want to keep the window open when running an executable that you create, you will need to add some code to suspend execution and keep the window open. Below, we show one example of how to keep the window open by adding this line of code before the return statement:

system("pause");

The one objection I have to this method is that the system() function is not part of the C++ standard and may not be valid with some C++ compilers.

#include <iostream>

int main()
{
    using namespace std;

    cout << "Hello World!" << endl;

    system("pause");
    return 0;
}

Alternatively, we could use cin.get(); to keep the window open like this:

#include <iostream>

int main()
{
    using namespace std;

    cout << "Hello World!" << endl;

    cin.get();
    return 0;
}

However, using cin.get() can have problems if input is taken directly before it. The problem is that the input in the stream carries over to the cin.get() and causes the program to exit. To prevent this, we can add a call to clear() and ignore(), as we do below.

#include <iostream>

int main()
{
    using namespace std;

    int iInt;
    cin >> iInt;
    cout << "Input = " << iInt << endl;

    cin.clear();
    cin.ignore(0xFFFFFFFF, '\n');
    cin.get();
    return 0;
}