How to Set Dialog as TopMost Window?

11 10 2009


I always wondered about popularity of Winamp. It has rich custom drawn UI, which made it stand out of the crowd. Did you noticed its “Always on top” feature and wondered about how its implemented? Its time to reveal the secret – How winamp implemented that feature – Staying at the top?

SetTopMostWindow


You can use – SetWindowPos() with HWND_TOPMOST flag. Have a look at the code snippet.

void CRabbitDlg::OnSetTopmost()
{
    // Set window position to topmost window.
    ::SetWindowPos( GetSafeHwnd(),
                    HWND_TOPMOST,
                    0, 0, 0, 0,
                    SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSIZE );
}


Single line of code. But wowing feature. isn’t it?


Targeted Audience – Beginners.





How to Watch this Pointer – The Wizards Way!

30 07 2009


How to watch the this pointer? Just add ‘this’ to watch window. Everyone does like that. Isn’t it? But how Visual C++ wizards watch ‘this’ pointer? ;)

thiswizardway


The secret is, visual C++ compiler passes this pointer via ECX register. So add (ClassName*)(@ECX) to watch window will give you this pointer. Have a look at the screenshot.

thiswizardway2


Interesting, the internals of Visual C++. Isn’t it?


Targeted Audiance – Intermediate.





How to get the CPU Name String?

21 06 2009


While taking the System properties, you have noticed the processor name string. For instance, in my laptop it is – “Intel(R) Core(TM)2 Duo CPU     T5250  @ 1.50GHz“. Ever though about how to get this processor name string?

cpuid
Image Courtesy – Wallpaper Mania.


You can use the function – __cpuid(), which generates the instruction – cpuid. Have a look at the code snippet. Code taken and modified from MSDN.

#include <iostream>
#include <intrin.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    // Get extended ids.
    int CPUInfo[4] = {-1};
    __cpuid(CPUInfo, 0x80000000);
    unsigned int nExIds = CPUInfo[0];

    // Get the information associated with each extended ID.
    char CPUBrandString[0x40] = { 0 };
    for( unsigned int i=0x80000000; i<=nExIds; ++i)
    {
        __cpuid(CPUInfo, i);

        // Interpret CPU brand string and cache information.
        if  (i == 0x80000002)
        {
            memcpy( CPUBrandString,
            CPUInfo,
            sizeof(CPUInfo));
        }
        else if( i == 0x80000003 )
        {
            memcpy( CPUBrandString + 16,
            CPUInfo,
            sizeof(CPUInfo));
        }
        else if( i == 0x80000004 )
        {
            memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
        }
}

    cout << "Cpu String: " << CPUBrandString;
}


You can get a lot of information about cpu by using __cpuid. Have a look at the MSDN Documentation.


Targeted Audiance – Intermeidate.





How to Change the Icon of MFC application?

5 04 2009


When you create an MFC application, did you notice the icon of executable? Yes! its that same old icon. But I’ve seen other application with different icon. Well, how to set the icon of executable to give a new face for it? ;)

setappicon
Image Courtesy – Flickr


The secret is, windows will choose the first icon present in executable as exe icon. By default for an MFC application, IDR_MAINFRAME will be the icon resource name and it have the lowest resource value – 128. Follow the steps to add an icon and make set it the first one in executable.

1. Import a new icon by using resource editor.

setappicon1

2. Let the icon be IDR_ICON1.
3. Now open resource.h and you can see, IDR_MAINFRAME which is the mfc icon, have lowest resource id.

setappicon2
4. Now edit the resource.h to make IDI_ICON1 as lowest resource id.

setappicon3
5. Now clean and build your application and check the application icon. Wow! its changed!!!


The point is, the icon should be the first icon in executable. You can set icon value even to zero. It will work!


Targeted Audiance – Intermediate.





How to measure Performance by using High Resolution Timer in Visual C++?

31 03 2009


Ever had a performance tweaking project? The first thing you need is a high resolution stop watch to measure performance of different code blocks. But is there a high resolution stop watch?

highperformancetimer


You can use QueryPerformanceCounter(). You can get the performance counter frequency – i.e. ticks per second by calling QueryPerformanceFrequency(). Have a look at the sample CStopWatch class.

// Stop watch class.
class CStopWatch
{
public:
    // Constructor.
    CStopWatch()
    {
        // Ticks per second.
        QueryPerformanceFrequency( &liPerfFreq );
    }

    // Start counter.
    void Start()
    {
        liStart.QuadPart = 0;
        QueryPerformanceCounter( &liStart );
    }

    // Stop counter.
    void Stop()
    {
        liEnd.QuadPart = 0;
        QueryPerformanceCounter( &liEnd );
    }

    // Get duration.
    long double GetDuration()
    {
        return ( liEnd.QuadPart - liStart.QuadPart) /
                long double( liPerfFreq.QuadPart );
    }

private:
    LARGE_INTEGER liStart;
    LARGE_INTEGER liEnd;
    LARGE_INTEGER liPerfFreq;
};

int main()
{
    // Stop watch object.
    CStopWatch timer;

    // Start timer.
    timer.Start();

    // ZZzzzzz... for few seconds.
    Sleep( 3000 );
    timer.Stop();

    // Get the duration. Duration is in seconds.
    long double duration = timer.GetDuration();

    return 0;
}


Even if the sample app slept for 3 seconds, in high resolution timer, the duration is 2.9xxx seconds. ;) Can you guess why?


Targeted Audiance – Intermediate.





How to Set Console Text Color?

29 03 2009


Getting bored with the black and white console? Did you ever wish to change the text or background color of console?

setconsoletextcolor
Image Courtesy – reginadowntown.


Yes! You can use the api – SetConsoleTextAttribute(). See the code snippet below.

// Set text color as Yellow with white background.
SetConsoleTextAttribute(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    FOREGROUND_INTENSITY              | // Set Text color
    FOREGROUND_RED | FOREGROUND_GREEN | // Text color as Yellow.
    BACKGROUND_INTENSITY              | // Set Background color
    BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE ); // White Bg.


Please note that you can mix red/green/blue constants to make new colors. Have fun. :)


Targeted Audience – Beginners.





How to blink LED’s in Keyboard?

12 03 2009


Do you remember those golden DOS days, where we access the video RAM directly and set the status of NumLock, ScrollLock etc and blink the LED of keyboard. Now in modern windows environment we are no more allowed to access the video RAM directly. But is there any way to blink the keyboard LEDs as we did before?

keyboardblinking


Yes. The trick is to send NumLock keystroke event by using keybd_input() function. See the sample code snippet from MSDN.

// Set NUMLOCK Status.
void SetNumLock( BOOL bState )
{
    BYTE keyState[256];

    GetKeyboardState((LPBYTE)&keyState);
    if( (bState && !(keyState[VK_NUMLOCK] & 1)) ||
        (!bState && (keyState[VK_NUMLOCK] & 1)) )
    {
        // Simulate a key press
        keybd_event( VK_NUMLOCK,
                     0x45,
                     KEYEVENTF_EXTENDEDKEY | 0,
                     0 );

        // Simulate a key release
        keybd_event( VK_NUMLOCK,
                     0x45,
                     KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
                     0);
    }
}

// Blink NUMLOCK.
void BlinkNumLock()
{
    // Blink status.
    bool bBlink = false;

    // Blink the NUMLOCK periodically.
    while( true )
    {
        SetNumLock( bBlink );
        bBlink = !bBlink;
        Sleep( 100 );
    }
}

You can also use SendInput(), which is the latest version of keybd_event() to simulate keystrokes.

And one more thing, I was searching for an image for this post, but couldn’t find a suitable one. And this image is suggested by my wife. :) How is it? Did you like it? She would like to hear from you ;)


Targeted Audiance – Intermediate.





How to set Font for Static Text Controls?

4 03 2009


By default, static text is displayed in normal fonts. And you don’t have any option to make it bold or italic or underline. Is there any way to enable these styles and change the font of the static text control?

staticfont


Yes! you can do it. First you’ve to get the current font of the text control and then enable the styles you need then set it back. Setting font is done in OnInitDialog() and new font is kept as member variable. See the code snippet below.

BOOL CStaticFontDlg::OnInitDialog()
{
	...

    // Get current font.
    CFont* pFont = GetDlgItem( IDC_STATIC_ITALIC )->GetFont();
    LOGFONT LogFont = { 0 };
    pFont->GetLogFont( &LogFont );

    // Create new font with underline style.
    LogFont.lfUnderline = TRUE;
    m_StaticFont.CreateFontIndirect( &LogFont );

	// Sets the new font back to static text.
    GetDlgItem( IDC_STATIC_ITALIC )->SetFont( &m_StaticFont );

	return TRUE;
}

Now the static text will look like this.

staticfont3


Don’t forget to change the Id of static text control from IDC_STATIC to something else. Or else GetDlgItem() will return invalid handle.


Targeted Audiance – Intermediate.





gotoxy() function in Visual C++?

1 03 2009


I often feel nostalgic about the gotoxy() function in old Turbo C++. The gotoxy() is used to “jump” to any point of the console screen. I used that function to create nice menu effects. But unfortunately in visual C++, gotoxy() is not available. But is there any other api which can be used instead of gotoxy()?

gotoxy1


You can use SetConsoleCursorPosition(). Check out the following sample program. It reads an integer in loop and prints the time in the right hand corner of console. Just a demonstration of Visual C++’s gotoxy().

gotoxy2

#include "iostream"
#include "time.h"
#include "windows.h"

using namespace std;

// Set current cursor position.
void GotoXY( HANDLE StdOut, SHORT x, SHORT y )
{
    // Set the cursor position.
    COORD Cord;
    Cord.X = x;
    Cord.Y = y;
    SetConsoleCursorPosition( StdOut, Cord );
}

// Print time at the upper right corner of console.
void PrintTime()
{
    // Get handle to console output buffer.
    HANDLE hStdout = GetStdHandle( STD_OUTPUT_HANDLE );  

    // Get current screen information.
    CONSOLE_SCREEN_BUFFER_INFO ScreenBufferInfo = { 0 };
    GetConsoleScreenBufferInfo( hStdout, &ScreenBufferInfo ); 

    // Set the cursor position to upper-right of console.
    GotoXY( hStdout, 50, 0 );

    // Get time and display it.
    time_t tim=time(NULL);
    char *s=ctime(&tim);
    cout << s; 

    // Reset cursor back to position.
    GotoXY( hStdout,
            ScreenBufferInfo.dwCursorPosition.X,
            ScreenBufferInfo.dwCursorPosition.Y );
} 

void main(int argc, char* argv[])
{
    // Just to provide enough space.
    cout << endl << endl; 

    while( true )
    {
        // Print the time.
        PrintTime(); 

        // Read a value.
        int a;
        cout << "Enter number: ";
        cin >> a;
    }
}


Yes! After a short break, I’m back. :) You’ll soon have a happy news from me, within a week. ;) Keep watching.


Targeted Audience – Beginners.





How to Enable XP/Vista themes in your Dialog?

30 12 2008


From Windows XP onwards, the basic control look and feel have improved drastically. Previously, they were merely flat style controls without any effects- the maximum you can do is to change the control color and mouse cursor icon( I hope you do remember the Jungle Theme of those old win98 days). In Vista its even more stylish. But is it possible to give the same look & feel effects to our applications as well?

xp_themes


Yes. You can. You just have to add a manifest file to your application. Well follow the detailed steps about how to do it. Well, we are going to apply Vista look and feel to the following dialog. ;)

xp_theme_7

1) The manifest format is specified below. Copy it to notepad and change the “ExeName” to the name of your application. For instance if your exename is Rabbit.exe, then “ExeName” is “Rabbit”.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
    version="1.0.0.0"
    processorArchitecture="X86"
    name="ExeName"
    type="win32"
/>
<description>Application Description</description>
<dependency>
    <dependentAssembly>
        <assemblyIdentity
            type="win32"
            name="Microsoft.Windows.Common-Controls"
            version="6.0.0.0"
            processorArchitecture="X86"
            publicKeyToken="6595b64144ccf1df"
            language="*"
        />
    </dependentAssembly>
</dependency>
</assembly>

2) Now insert a new resource.

xp_theme_1
3) Now add a new Custom Resource with Resource ID as 24.

xp_theme_2

4) Now copy-paste the manifest contents to new resource and save it. Make sure you’ve changed the “ExeName” to your application name.

xp_theme_3

5) Now take the properties of our new resource -  “IDR_DEFAULT1″.

xp_theme_4

6) Now change the Resource ID to “1“.

xp_theme_5

7) That’s it. Now compile and run the application. And now see the command buttons in Vista Style. Cool! isn’t it?

xp_theme_6


I searched a lot for the screenshot of the old “Jungle Theme” of Windows 98. Its a pity that I couldn’t find it. :( If you find one such, please do notify. I’m getting nostalgic. ;)


Targeted Audience – Intermediate.








Follow

Get every new post delivered to your Inbox.