Building Unicode applications in MFC(转载)

What's The Point?
Windows NT4 and 2K run on Unicode. A great many of the net API functions provided by Microsoft® require Unicode and translating strings in and out of Unicode just to push them through these functions is a real pain. Building an application in Unicode not only allows easier access to these functions, but also creates code that runs optimally on NT operating systems.

NOTE - western releases of W9x don't support unicode. All releases of W9x only support a limited set of administrative net API calls which, as well as being ASCII, are often structured differently to their NT equivalents. The help files are fairly useless on leading you through the differences. The best way is to examine the respective header files for the function structures.

Project Settings
The first thing to ensure is that you have included the necessary Unicode libraries when installing your copy of Microsoft Visual Studio®. If you didn't do this when you first installed the tool, it's time to go back and remedy the omission.

Now you can go ahead and get the App Wizard to build you a project. Don't worry about Unicode for the moment, just work your way through the wizard as normal.

Once you've got a basic project up and running, all you need to do to make it build in Unicode is to tweak a couple of project settings. For debug builds, change the preprocessor directive to that shown below:

For release builds, change the preprocessor directives to that shown below:

If what you see in the preprocessor definitions box is substantially different from what you see above, don't panic. All you are trying to do is replace "_MBCS" with "_UNICODE" at the end of the string.

Finally you need to change the entry point symbol in the linker options:

Now the application will build using the Unicode libraries.

But this is only the first step. Now that the application builds in Unicode, you can't go on using the same old ASCII-type functions you always did. A little more refinement is required and here are a few hints on how to do it.

Unicode Programming
First of all, use MFC classes, particularly CStrings, wherever possible. They are overloaded to deal with both ASCII and Unicode.

When using string literals, you need to use the _T( ) macro to get the necessary conversion e.g.

AfxMessageBox(_T("This is a converted Unicode string literal"));

When using printf or the CString.Format() member function, the whole quoted section must be encapsulated by the _T( ) macro:

CString sExample;
sExample.Format(_T("Function failed, error code is %d"), GetLastError());

Don't use char[] types, use TCHAR[] instead (if you can't use a CString).

Below is a brief summary of some standard C++ function calls and their Unicode equivalents.

ASCII Unicode
strlen wcslen
strcpy wcscpy
itoa itow
atoi _wtoi
printf wprintf








And that, as they say, is all there is to it!

posted on 2005-05-13 09:53  Michael Zhao  阅读(631)  评论(0编辑  收藏  举报