Wednesday 21 December 2011

Disabling the screen saver

At some point in a programmers life, he or she must learn how to disable the screen saver through code. Earlier the way used to be to install a WH_GETMESSAGE windows hook and monitor the WM_SYSCOMMAND message. If the wParam of the message would be SC_SCREENSAVE, you would not let the message do anything by returning either 1 or 0 or any value(I don't remember exactly). But for Windows Vista and above, Microsoft says that the screen saver will be activated no matter what an application does to the SC_SCREENSAVE message.
That is where the problem rises now. A solution is that one can set a timer for his application using SetTimer() windows API function and then when the WM_TIMER message arrives after a specified time out, he can simulate a key press event on keyboard using keybd_event() windows API function. This way windows will continuously receive key press events after a specified time out and thus the screen saver will not be activated. A word of caution: you need to make sure that the time out specified in SetTimer() function should be less than 60 seconds ideally because the minimum time that can be set for screen saver under windows is 60 seconds.
Below is a program snippet that shows the window procedure function in which first the timer is set during dialog initialization, and WM_TIMER messages are processed.

BOOL CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
        case WM_INITDIALOG:
            SetTimer(hwndDlg, 100, 45000, NULL);
            return TRUE;

        case WM_CLOSE:
            EndDialog(hwndDlg, 0);
            return TRUE;

        case WM_TIMER:
            //Simulate a key press
            keybd_event(VK_F16, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
            //Simulate a key release
            keybd_event(VK_F16, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
            return 0;
   
        case WM_COMMAND:
            ..........................
            ..........................
            ..........................

        return FALSE;
    }

When the window procedure first receives the WM_INITDIALOG message, the timer is set to 45000 millisecons(45 seconds). 100 passed as the second parameter is the timer ID and is used if more than one timer was used. Here it can be any value.
Inside the WM_TIMER case, I have first simulated a key press of a virtual F16 key. Then there is the simulation of a key release of the same key. Thus a simulation of a key press of F16 key takes place after every 45 sconds. This ensures that the screen saver is never activated.
For more information on SetTimer and keybd_event functions, see the following links:
SetTimer
keybd_event

Please update me if you find any errors or outdated information in this post.

Nearly True Random Number Generator

The concept of generating random numbers is very important in many scenarios such as in encryption. The normal procedure to generate random numbers is to first use srand() function to seed the random number generator and then use the rand() function repeatedly to generate a pseudorandom number sequence. You can google it and find many such examples. But the problem in such an approach is that each time the seed is same, the same pseudorandom number sequence will be generated. This is a big problem in situations in which the programmer wants somewhat real randomness such as in encryption. One way to get around this problem is to utilize the current date and time to introduce somewhat real randomness in the system. The program snippet that demonstrates this is given below:

#include <windows.h>
#include <stdio.h>

int main()
{
    SYSTEMTIME lt;
    GetLocalTime(&lt);
    int ran, i;
    ran = 10000 * lt.wMilliseconds + 1000 * lt.wSecond + 100 * lt.wMinute + 10 * lt.wHour + lt.wDay;
    srand(ran);
    printf("10 nearly true random numbers:\n");
    for(i = 0; i < 10; i++)
    {
           printf("%d\t", rand());
     }
    return 0;
}

SYSTEMTIME is a structure that can hold date and time. First we define a struct lt of this type. Then we use the GetLocalTime() windows API function which takes the address of  lt as argument to fill this structure with current date and time. Next, the current Milliseconds, second, minute, hour and day are all added after multiplying each by some factor (10, 000, 1000, 100, 10, 1 respectively) and the result is stored in an integer ran. Randomness is actually generated right here. This number ran is used to seed the random number generator. Thus, now each time you execute the program, the random number sequence generated will be different. This trick can also be applied to cure the problems in real programming situations as already mentioned.

Tuesday 20 December 2011

First GUI application in Code Blocks

This tutorial is about creating the first GUI (Graphical User Interface) application in Code Blocks IDE(see the Necessary tools page). Follow these steps:
Step 1:
Run Code Blocks.


Step  2:
Click on the Create a new project link.

Step 3:
Select Win32 Gui Project in the window that appears.

Step 4:
Click on Go button. In the wizard that appears, click next and then under "Select a project type", select "Dialog based"(selected by default). Click next. Type a project title and then keep all as it is. Lastly, click finish.

Step 5:
On the left side, you can see the main.cpp file that contains the actual code that runs the program. Plus, there is a resource.h header file and a resource.rc resource file.

Step 6:
Click on the build icon. Once the project is built, click on the run icon.
Congratulations, you have run your first windows GUI application.
A screen shot of the application is shown below:


Like main() is the entry point of a program in normal C programs, so is WinMain() in win32 programs. resource.rc file contains our dialog design information. In other words, it is the dialog box here. A detailed discussion on what exactly the parameters are, the resource.rc file and other things will make the post lengthy. Instead, I post below some good links for you to further grasp the concepts.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms633559%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/bb384843.aspx

For the call back function DialogProc(name can be different), see the WindowProc function at msdn at the link below:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573%28v=vs.85%29.aspx

For resource files:
http://msdn.microsoft.com/en-us/library/zabda143%28v=vs.80%29.aspx

There is also a free resource editor that allows you to graphically design the dialog. Download it from  http://www.resedit.net/. Now run the resource editor, browse to the resource.rc file and open with it. Bring some changes in it. Save it, and rebuild the application. Now see that the changes you made are reflected in the dialog box.

Rest is left for the reader to explore.
Constructive criticism and suggestions are welcome.

Finding Armstrong numbers in a given range

If the sum of cubes of each digit of a number is equal to the number, then the number is called as Armstrong number. Today's program is also based on Armstrong numbers.
Q. Print all Armstrong numbers in a given range entered by the user.
Sol:

#include <stdio.h>

int CountDigits(int num);    //returns the number of digits in a number
int SumOfCubes(int numberofdigits, int number);   //Finds the sum of cubes of the digits in a number

int main()
{
    printf("Enter the range. Lower number first followed by the upper number of the range\n");
    int low, high;
    scanf("%d%d", &low, &high);
    int i, count, sum;
    printf("The numbers in this range which are Armstrong are:\n\n");
    for(i = low; i <= high; i++)
    {
        count = CountDigits(i);
        sum = SumOfCubes(count, i);
        if(sum == i)
          printf("%d\n", i);
    }

    return 0;
}

int SumOfCubes(int numberofdigits, int number)
{
    int digarray[15];     //This array will contain the digits in the number
    int i;
    for(i = 0; i < numberofdigits; i++)
    {
        digarray[i] = number % 10;      //Fill the digarray with individual digits
        number /= 10;
    }

    int sum = 0, j;
    for(j = 0; j < numberofdigits; j++)
    {
        sum = sum + (digarray[j] * digarray[j] * digarray[j]);  //Find sum of cubes of digits
    }

    return sum;
}

int CountDigits(int num)
{
    int i = 0;
    while(num)
    {
        num /= 10;
        i++;
    }

    return i;
}

Sample output:




Most of the program is self explanatory. Rest of the things have been cleared by comments. Please leave comments if you want to make any correction or suggest a new concept.

Sunday 18 December 2011

Learn to use the command line parameters

You may have often seen programs that take command line arguments. If you have ever wondered about how to write a program that would utilize these arguments then this is the post for you. Command line arguments are passed as strings to your program even if the argument is a number. Suppose your program takes unknown numbers as CL arguments and you need to add them and print the result. How would you do it. Below is the complete program that demonstrates this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int i, sum = 0;
    for(i = 1; i < argc; i++)         //Loop through argv[] to find the sum of arguments
    {
        sum += atoi(argv[i]);        //convert argument argv[i] to integer and add to previous sum
    }

    printf("Sum is %d\n", sum);
    return 0;
}

The command line information is passed to our program in two variables: argc and argv. argc contains the number of arguments passed. argv[] contains the arguments in the form of strings. Thus, argv[0] is the first argument, argv[1] second and so on. However, remember that even if no arguments are passed, argc is always 1. This is because the program name itself is always passed to the program by the operating system. This argument is stored in argv[0] always. Thus, the arguments that we actually want here start from argv[1]. Now if we analyze the code in the light of this information, we should be able to understand it. Please feel free to ask or give suggestions if anything is not clear.

Finding the number of digits in a number

Below is the program for finding the number of digits in a number.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int num;
    printf("Enter the number\n");
    scanf("%d", &num);
    int i = 0;
    while(num)                       
    {
        num = num / 10;       //Repetitively divide the number until num is zero. Then, loop will end.
        i++;
    }

    printf("The number of digits in number is %d\n", i);
    return 0;
}

Please feel free to give your suggestions or make some corrections.

Saturday 17 December 2011

An introduction to this blog

This blog is for those who want to read tutorials on C/C++, Visual C++ with good coverage. It assumes that you have a basic working knowledge of C/C++. In the "necessary tools" page, you will also find information on where to find the necessary tools for programming in the different environments.
At last I hope that my posts will be helpful for mainly beginners and somewhat to intermediate programmers.