- chcp chcp
- Синтаксис Syntax
- Параметры Parameters
- Комментарии Remarks
- Примеры Examples
- Использование кодовой страницы UTF-8 Use the UTF-8 code page
- — API-интерфейсы и-W -A vs. -W APIs
- Задание кодовой страницы процесса UTF-8 Set a process code page to UTF-8
- Примеры Examples
- Преобразование кодовой страницы Code page conversion
- Кодовые страницы консоли Console Code Pages
- EnumSystemCodePagesA function (winnls.h)
- Syntax
- Parameters
- Return value
- Remarks
chcp chcp
Изменяет активную кодовую страницу консоли. Changes the active console code page. Если используется без параметров, параметр chcp отображает номер активной кодовой страницы консоли. If used without parameters, chcp displays the number of the active console code page.
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
Задает кодовую страницу. Specifies the code page. | |
/? /? | Отображение справки в командной строке. Displays help at the command prompt. |
В следующей таблице перечислены поддерживаемые кодовые страницы и их страны, регионы или языки. The following table lists each supported code page and its country/region or language:
Кодовая страница Code page | Страна, регион или язык Country/region or language |
---|---|
437 437 | США United States |
850 850 | Многоязычная (латиница I) Multilingual (Latin I) |
852 852 | Славянские (латиница II) Slavic (Latin II) |
855 855 | Кириллица (Русский) Cyrillic (Russian) |
857 857 | Турецкий Turkish |
860 860 | Португальский Portuguese |
861 861 | Исландский Icelandic |
863 863 | Canadian-French Canadian-French |
865 865 | Скандинавская Nordic |
866 866 | русском языке Russian |
869 869 | Современный греческий Modern Greek |
936 936 | Китайский Chinese |
Комментарии Remarks
В окне командной строки, использующем растровые шрифты, правильно отображается только кодовая страница изготовителя оборудования (OEM), установленная вместе с Windows. Only the original equipment manufacturer (OEM) code page that is installed with Windows appears correctly in a Command Prompt window that uses Raster fonts. Другие кодовые страницы отображаются правильно в полноэкранном режиме или в окнах командной строки, в которых используются шрифты TrueType. Other code pages appear correctly in full-screen mode or in Command Prompt windows that use TrueType fonts.
Вам не нужно подготавливать кодовые страницы (как в MS-DOS). You don’t need to prepare code pages (as in MS-DOS).
Программы, запускаемые после назначения новой кодовой страницы, используют новую кодовую страницу. Programs that you start after you assign a new code page use the new code page. Однако программы (кроме Cmd.exe), которые вы начали перед назначением новой кодовой страницы, продолжат использовать исходную кодовую страницу. However, programs (except Cmd.exe) that you started before assigning the new code page will continue to use the original code page.
Примеры Examples
Чтобы просмотреть текущую настройку кодовой страницы, введите: To view the active code page setting, type:
Появится сообщение следующего вида: Active code page: 437 A message similar to the following appears: Active code page: 437
Чтобы изменить активную кодовую страницу на 850 (многоязычный), введите: To change the active code page to 850 (Multilingual), type:
Если указанная кодовая страница является недопустимой, появляется следующее сообщение об ошибке: Invalid code page If the specified code page is invalid, the following error message appears: Invalid code page
Использование кодовой страницы UTF-8 Use the UTF-8 code page
Используйте кодировку UTF-8 для обеспечения оптимальной совместимости между веб-приложениями и другими * платформами на основе nix (UNIX, Linux и разновидности), свести к сведению ошибки локализации и снизить затраты на тестирование. Use UTF-8 character encoding for optimal compatibility between web apps and other *nix-based platforms (Unix, Linux, and variants), minimize localization bugs, and reduce testing overhead.
UTF-8 — это универсальная кодовая страница для интернационализации и способная кодировать весь набор символов Юникода. UTF-8 is the universal code page for internationalization and is able to encode the entire Unicode character set. Он используется в Интернете по умолчанию, а также на платформах на основе NIX. It is used pervasively on the web, and is the default for *nix-based platforms.
Закодированный символ занимает от 1 до 4 байт. An encoded character takes between 1 and 4 bytes. Кодировка UTF-8 поддерживает более длинные последовательности байтов (до 6 байт), но большая кодовая точка Юникода 6,0 (U + 10FFFF) занимает всего 4 байта. UTF-8 encoding supports longer byte sequences, up to 6 bytes, but the biggest code point of Unicode 6.0 (U+10FFFF) only takes 4 bytes.
— API-интерфейсы и-W -A vs. -W APIs
Интерфейсы API Win32 часто поддерживают варианты «-A» и «W». Win32 APIs often support both -A and -W variants.
— Варианты, распознаваемые кодовую страницу ANSI, настроенную для системы и поддержки char* , а варианты-W работают в кодировке UTF-16 и поддерживают WCHAR . -A variants recognize the ANSI code page configured on the system and support char* , while -W variants operate in UTF-16 and support WCHAR .
До недавнего времени Windows выделена «Юникод»-W Variant для API. Until recently, Windows has emphasized «Unicode» -W variants over -A APIs. Однако последние выпуски использовали кодовую страницу ANSI и — API-интерфейсы в качестве средства для поддержки приложений в кодировке UTF-8. However, recent releases have used the ANSI code page and -A APIs as a means to introduce UTF-8 support to apps. Если кодовая страница ANSI настроена для UTF-8, то API-интерфейсы работают в кодировке UTF-8. If the ANSI code page is configured for UTF-8, -A APIs operate in UTF-8. Эта модель имеет преимущество поддержки существующего кода, построенного с помощью API-интерфейсов, без изменения кода. This model has the benefit of supporting existing code built with -A APIs without any code changes.
Задание кодовой страницы процесса UTF-8 Set a process code page to UTF-8
Начиная с версии Windows 1903 (Май 2019), можно использовать свойство Активекодепаже в appxmanifest для упакованных приложений или манифест Fusion для неупакованных приложений, чтобы заставить процесс использовать UTF-8 в качестве кодовой страницы процесса. As of Windows Version 1903 (May 2019 Update), you can use the ActiveCodePage property in the appxmanifest for packaged apps, or the fusion manifest for unpackaged apps, to force a process to use UTF-8 as the process code page.
Вы можете объявить это свойство и целевой объект или выполнить его в более ранних сборках Windows, но необходимо как обычно выполнять обнаружение и преобразование кодовых страниц прежних версий. You can declare this property and target/run on earlier Windows builds, but you must handle legacy code page detection and conversion as usual. При использовании минимальной целевой версии Windows версии 1903 кодовая страница процесса всегда будет UTF-8, поэтому можно избежать обнаружения и преобразования кодовой страницы прежних версий. With a minimum target version of Windows Version 1903, the process code page will always be UTF-8 so legacy code page detection and conversion can be avoided.
Примеры Examples
Манифест appx для упакованного приложения: Appx manifest for a packaged app:
Манифест Fusion для неупакованного приложения Win32: Fusion manifest for an unpackaged Win32 app:
Добавление манифеста в существующий исполняемый файл из командной строки с помощью команды mt.exe -manifest -outputresource: ;#1 Add a manifest to an existing executable from the command line with mt.exe -manifest -outputresource: ;#1
Преобразование кодовой страницы Code page conversion
Поскольку Windows изначально работает в UTF-16 ( WCHAR ), может потребоваться преобразовать данные UTF-8 в UTF-16 (или наоборот) для взаимодействия с API Windows. As Windows operates natively in UTF-16 ( WCHAR ), you might need to convert UTF-8 data to UTF-16 (or vice versa) to interoperate with Windows APIs.
MultiByteToWideChar и WideCharToMultiByte позволяют выполнить преобразование между UTF-8 и UTF-16 ( WCHAR ) (и другими кодовыми страницами). MultiByteToWideChar and WideCharToMultiByte let you convert between UTF-8 and UTF-16 ( WCHAR ) (and other code pages). Это особенно полезно, когда устаревший API Win32 может понимать только WCHAR . This is particularly useful when a legacy Win32 API might only understand WCHAR . Эти функции позволяют преобразовать входные данные UTF-8 в WCHAR для передачи в API-интерфейс, а затем преобразовать все результаты при необходимости. These functions allow you to convert UTF-8 input to WCHAR to pass into a -W API and then convert any results back if necessary. При использовании этих функций с CodePage параметром CP_UTF8 , имеющим значение, используйте dwFlags либо 0 или MB_ERR_INVALID_CHARS , в противном случае — ERROR_INVALID_FLAGS . When using these functions with CodePage set to CP_UTF8 , use dwFlags of either 0 or MB_ERR_INVALID_CHARS , otherwise an ERROR_INVALID_FLAGS occurs.
CP_ACP«CP_UTF8 соответствует только в том случае, если работает в Windows версии 1903 (май 2019) или выше, а описанное выше свойство активекодепаже имеет значение UTF-8. CP_ACP equates to CP_UTF8 only if running on Windows Version 1903 (May 2019 Update) or above and the ActiveCodePage property described above is set to UTF-8. В противном случае она учитывает устаревшую системную кодовую страницу. Otherwise, it honors the legacy system code page. Рекомендуется использовать CP_UTF8 явно. We recommend using CP_UTF8 explicitly.
Кодовые страницы консоли Console Code Pages
Кодовая страница — это сопоставление кодов символов 256 с отдельными символами. A code page is a mapping of 256 character codes to individual characters. Разные кодовые страницы включают разные специальные символы, как правило, настроенные для языка или группы языков. Different code pages include different special characters, typically customized for a language or a group of languages.
С каждой консолью связаны две кодовые страницы: одна для ввода и одна для выхода. Associated with each console are two code pages: one for input and one for output. Консоль использует страницу входного кода для преобразования ввода с клавиатуры в соответствующее символьное значение. A console uses its input code page to translate keyboard input into the corresponding character value. Он использует свою кодовую страницу вывода для преобразования символьных значений, записанных различными функциями вывода, в изображения, отображаемые в окне консоли. It uses its output code page to translate the character values written by the various output functions into the images displayed in the console window. Приложение может использовать функции сетконсолекп и жетконсолекп для установки и получения кодовых страниц входного кода консоли и функций сетконсолеаутпуткп и GetConsoleOutputCP для установки и получения страниц с выходным кодом. An application can use the SetConsoleCP and GetConsoleCP functions to set and retrieve a console’s input code pages and the SetConsoleOutputCP and GetConsoleOutputCP functions to set and retrieve its output code pages.
Идентификаторы кодовых страниц, доступных на локальном компьютере, хранятся в реестре в следующем разделе: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage The identifiers of the code pages available on the local computer are stored in the registry under the following key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
Сведения об использовании функций реестра для определения доступных кодовых страниц см. в разделе Registry. For information about using the registry functions to determine the available code pages, see Registry.
Рекомендуется для всех новых и обновленных приложений командной строки, чтобы избежать кодовых страниц и использовать Юникод. It is recommended for all new and updated command-line applications to avoid code pages and use Unicode. Форматированный текст UTF-16 можно отправить в семейство API-интерфейсов для W консоли. UTF-16 formatted text can be sent to the W family of console APIs. Отформатированный текст UTF-8 можно отправить в семейство интерфейсов API консоли после того, как вы убедитесь, что кодовая страница имеет значение 65001 (CP_UTF8) с функциями сетконсолекп и сетконсолеаутпуткп . UTF-8 formatted text can be sent to the A family of console APIs after ensuring the code page is first set to 65001 (CP_UTF8) with the SetConsoleCP and SetConsoleOutputCP functions.
EnumSystemCodePagesA function (winnls.h)
Enumerates the code pages that are either installed on or supported by an operating system.
Syntax
Parameters
Pointer to an application-defined callback function. The EnumSystemCodePages function enumerates code pages by making repeated calls to this callback function. For more information, see EnumCodePagesProc.
Flag specifying the code pages to enumerate. This parameter can have one of the following values, which are mutually exclusive.
Value | Meaning |
---|---|
CP_INSTALLED | Enumerate only installed code pages. |
CP_SUPPORTED | Enumerate all supported code pages. |
Return value
Returns a nonzero value if successful, or 0 otherwise. To get extended error information, the application can call GetLastError, which can return one of the following error codes:
- ERROR_BADDB. The function could not access the data. This situation should not normally occur, and typically indicates a bad installation, a disk problem, or the like.
- ERROR_INVALID_FLAGS. The values supplied for flags were not valid.
- ERROR_INVALID_PARAMETER. Any of the parameter values was invalid.
Remarks
This function enumerates the code pages by passing code page identifiers, one at a time, to the specified application-defined callback function. This process continues until all installed or supported code page identifiers have been passed to the callback function, or the callback function returns FALSE.
When an application is using this function to determine an appropriate code page for saving data, it should use Unicode when possible. Other code pages are not as portable as Unicode between vendors or operating systems, due to different implementations of the associated standards.
The winnls.h header defines EnumSystemCodePages as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.