VB6 isn't using Unicode, most of the time

by Michael S. Kaplan, published on 2005/05/07 11:01 -04:00, original URI: http://blogs.msdn.com/b/michkap/archive/2005/05/07/415376.aspx

Last month, Christoph Guentner asked in the microsoft.public.win32.programmer.international newsgroup:

I use the winapi function ReadFile() to receive strings (bytes) from the serial port in my VB6 program. This works fine in most cases.

But when I receive binary data on system with languages settings chinese (simple) set as default, the function ReadFile() returns false strings!?

I use win2k and have set in the control panel->language settings-> 1st tab: scheme: english (USA)  language settings for the system: chinese (simple) as standard

In this case the string returned by ReadFile() returns e.g. ascii &h00 instead of ascii &h80.

Is there a ReadFileW() function for wide ascii?

Or do I have to modify the DCB? In BuildCommDCB I have set in DCB the fBitFields to (&h1011), fBinary is set.

Sending and receiving text strings does work.

And sending binary data using the ApiFunction WriteFile() seems to work because the device (which is connected at the other side of the serial cable) answers. Well this could be a answer with an error as well, so I am not really sure.

This is same when I use the VB6 CommCtrl and not the winapi functions.

Thanks for any hint.


The problem here actually started back in VB 3.0, where the documented way to pass buffers to the Windows API was to use the String datatype. A whole generation of Windows programmers used Strings in this way and everything worked.

And then Win32 came.

VB 4.0 (32-bit) made the jump to use Unicode for its String type, but had all API calls convert out of Unicode using the system default code page, so they could use the same code on all platforms. Now that code people used which had Strings as buffers would have weird problems as any String buffer would be converted out of Unicode in the function call. Sometimes it would work, sure. But other times, especially when the default system locale's default systme code page was MBCS, many of the byte seqences would be illegal. This is indeed the problem that Christoph was seeing.

My response to him was:

The problem is that you are sending the data as a string, and VB is converting that string via the default system code page. This means that some of the conversions will be to illegal byte sequences. This happens more often on an MBCS system, but can randomly happen other places too:


The key in this case is to not use a String datatype, but to use a byte array. This will avoid the many times that VB >= 4.0 and <= 6.0 will follow its own rules and convert those Strings which are not really strings at all....

no comments

Please consider a donation to keep this archive running, maintained and free of advertising.
Donate €20 or more to receive an offline copy of the whole archive including all images.

go to newer or older post, or back to index or month or day