古詩詞大全網 - 成語經典 - c# 處理某些占4個字節的漢字問題

c# 處理某些占4個字節的漢字問題

字符集GB18030是有4個字節的漢字,C#直接讀的話是亂碼,這種情況應該使用Windows API提供的函數來解決才行。

1.Windows API對GB18030-2000 的支持

下列 Windows API 提供對GB18030-2000 的支持。IsValidCodePage(), GetCPInfo(), MultiByteToWideChar() and WideCharToMultiByte().

具體說明如下:

1) IsValidCodePage(54936) returns TRUE.

2) GetCPInfo(54936, lpCPInfo) returns TRUE.

3) MultiByteToWideChar(54936, 0, lpMultiByteStr, cbMultiByte, lpWideCharStr, cchWideChar) 完成GB18030-2000 字符串 lpMultiByteStr 到 Unicode 字符串 lpWideCharStr 的轉換。

4) WideCharToMultiByte(54936, 0, lpWideCharStr, cchWideChar, lpMultiByteStr, cbMultiByte, lpDefaultChar, lpUsedDefaultChar) 完成Unicode 字符串 lpWideCharStr 到 GB18030-2000 字符串 lpMultiByteStr 的轉換。

2. GB18030 函數庫

微軟4字節字符集編碼支持包 (MS4BSP- Microsoft 4-byte Character Set Encoding Support Package) 提供了六個函數,這六個函數支持多字節編碼(多達4字節)的字符串。 這些API 是從Windows 95/98/Me 提供的WCHAR (Unicode) 函數集中精選出來的。函數名與相應的ANSI 和WCHAR(Unicode) 函數完全相同,只是後綴的’A’ 或’W’被’L’替代。這些函數的參數與相應的’A’版本函數的參數接口完全相同。該支持包可使基於936代碼頁的應用程序向GB18030 或其他4字節編碼的轉換更加快捷。

MS4BSP 在Windows XP 平臺的實現是作為壹個簡單的動態連接庫 – ms4bsp.dll。 每壹函數都通過調用MultiByteToWideChar() 函數將任何多字節字符串輸入參數轉換為UTF-16編碼格式,然後調用相應的 ‘W’ 版本的函數,返回該函數的輸出參數。該動態連接庫假設當前系統中存在相關的字體,輸入法(IME) 和註冊表的設置信息。

該函數集中的缺省4字節字符編碼為54936 (GB18030-2000). 將來版本的MS4BL 可能支持其他4字節編碼。

接口清單:

CODEBOOL ExtTextOutL(

HDC hdc, // handle to DC

int X, // x-coordinate of reference point

int Y, // y-coordinate of reference point

UINT fuOptions, // text-output options

CONST RECT* lprc, // optional dimensions

LPCSTR lpString, // string

UINT cbCount, // number of characters in string

CONST INT* lpDx // array of spacing values

);

BOOL GetTextExtentExPointL(

HDC hdc, // handle to DC

LPCSTR lpszStr, // character string

int cchString, // number of characters

int nMaxExtent, // maximum width of formatted string

LPINT lpnFit, // maximum number of characters

LPINT alpDx, // array of partial string widths

LPSIZE lpSize // string dimensions

);

BOOL GetTextExtentPoint32L(

HDC hdc, // handle to DC

LPCSTR lpString, // text string

int cbString, // characters in string

LPSIZE lpSize // string size

);

Int MessageBoxL(

HWND hWnd, // handle to owner window

LPCSTR lpText, // text in message box

LPCSTR lpCaption, // message box title

UINT uType // message box style

);

Int MessageBoxExL(

HWND hWnd, // handle to owner window

LPCSTR lpText, // text in message box

LPCSTR lpCaption, // message box title

UINT uType, // message box style

WORD wLanguageId // language identifier

);

BOOL TextOutL(

HDC hdc, // handle to DC

int nXStart, // x-coordinate of starting position

int nYStart, // y-coordinate of starting position

LPCSTR lpString, // character string

int cbString // number of characters

);