13

I have to convert the encoding of a string output of a VB6 application to a specific encoding.

The problem is, I don't know the encoding of the string, because of that:

According to the VB6 documentation when accessing certain API functions the internal Unicode strings are converted to ANSI strings using the default codepage of Windows.

Because of that, the encoding of the string output can be different on different systems, but I have to know it to perform the conversion.

How can I read the default codepage using the Win32 API or - if there's no other way - by reading the registry?

Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329

3 Answers3

22

It could be even more succinct by using GetACP - the Win32 API call for returning the default code page! (Default code page is often called "ANSI")

int nCodePage = GetACP(); 

Also many API calls (such as MultiByteToWideChar) accept the constant value CP_ACP (zero) which always means "use the system code page". So you may not actually need to know the current code page, depending on what you want to do with it.

Community
  • 1
  • 1
MarkJ
  • 30,070
  • 5
  • 68
  • 111
  • Thanks to whoever suggested the edit to mention "ANSI" and improve code formatting slightly. Good idea, I've edited it accordingly myself. – MarkJ Jul 27 '12 at 13:25
  • 1
    This usage of ANSI is quite nonsensical. The Windows code pages are often referred to as ANSI code pages, because they were intended to become standard; they never did though. Using then 'ANSI' to only refer to the default is highly confusing and I've never seen it used like this. – MicroVirus Oct 27 '15 at 12:06
2

GetSystemDefaultLCID() gives you the system locale.

If the LCID is not enough and you truly need the codepage, use this code:

  TCHAR szCodePage[10];
  int cch= GetLocaleInfo(
    GetSystemDefaultLCID(), // or any LCID you may be interested in
    LOCALE_IDEFAULTANSICODEPAGE, 
    szCodePage, 
    countof(szCodePage));

  nCodePage= cch>0 ? _ttoi(szCodePage) : 0;
Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
  • Or more succinctly, as in my answer: `int nCodePage=GetACP();` :) It's quite long-winded to get the name of the code page and then get the code page as a string and then convert to an integer – MarkJ Aug 15 '12 at 11:50
0

That worked for me, thanks, but can be written more succinctly as:

UINT nCodePage = CP_ACP;
const int cch = ::GetLocaleInfo(LOCALE_SYSTEM_DEFAULT,
     LOCALE_RETURN_NUMBER|LOCALE_IDEFAULTANSICODEPAGE,
     (LPTSTR)&nCodePage, sizeof(nCodePage) / sizeof(_TCHAR) );
Simeon Pilgrim
  • 22,906
  • 3
  • 32
  • 45
  • Or even more succinct, as in my answer: `int nCodePage=GetACP();` :) It's a bit long-winded to get the *name* of the code page and then look up the identifier code from the name – MarkJ May 08 '12 at 11:42