How to convert Unicode to Ansi and vice versa – More Easily?

7 05 2008


For converting between Unicode and Ansi and vice versa, usually we use functions such as MultiByteToWideChar() and WideCharToMultiByte(). But they are bit hard to use. Is there any other easy way to convert Unicode to Ansi and vice versa? Yes! you can use ATL conversion macros.


In ATL there are some helper macros defined such as W2A() which is used to convert widechar to ansi and A2W which is used to convert ansi to WideChar. Before using this macros you should initialize the conversion by calling USES_CONVERSION. See the code snippet below.

#include "atlconv.h"
...

// Ansi string.
char* pstrString = "Hello There!";

// Unicode string.
wchar_t* pUnicodeString = 0;

// Use this macro for Initializing the conversion.
// Actually, some member variable initialization deep inside.
USES_CONVERSION;

// Convert Ansi to Unicode.
pUnicodeString = A2W( pstrString);

// Convert Unicode to Ansi.
pstrString = W2A( pUnicodeString);


Targeted Audience – Beginners.





How to handle Ctrl+C in Console Applications?

7 05 2008


Some of our testapps or applications are console applications and testers usually crash those by applying Ctrl+C. This is because Console will forcefully terminate the application if it receives a Ctrl+C. For those situation, you can handle the Ctrl+C yourself and can do graceful exit.


You can use the function – SetConsoleCtrlHandler() to register a callback function to handle Ctrl+C events from the console. See the following code snippet.

BOOL CtrlHandler(DWORD dwCtrlType)
{
    if( CTRL_C_EVENT == dwCtrlType)
    {
        // Recd Ctrl+C. Write your clean up code here.
    }
}

void main()
{
    SetConsoleCtrlHandler(
      (PHANDLER_ROUTINE) CtrlHandler, // handler function
      TRUE); // add to list
}


Together with Ctrl+C you can handle more console events. See the list.

  • CTRL_CLOSE_EVENT
  • CTRL_LOGOFF_EVENT
  • CTRL_SHUTDOWN_EVENT
  • CTRL_BREAK_EVENT


Targeted Audience – Intermediate.