Getstdhandle c что это

от admin

Функции API для работы с консолью

Для начала работы с консолью необходимо получить ее дескриптор.

Функция получения дескриптора стандартного устройства ввода, вывода или ошибки в зависимости от переданного константного параметра:
HANDLE WINAPI GetStdHandle(__in DWORD nStdHandle);

nStdHandle может принимать значения

  • STD_INPUT_HANDLE = -10; // устройство ввода
  • STD_OUTPUT_HANDLE = -11; // устройство вывода
  • STD_ERROR_HANDLE = -12; // ошибка

Использование русского языка в консоли с помощью API

Для указания кодовой страницы используются функции

  • Кодовая страница консоли вывода
    BOOL WINAPI SetConsoleOutputCP(UINT wCodePageID);
  • Кодовая страница консоли ввода
    BOOL WINAPI SetConsoleCP(UINT wCodePageID);

где wCodePageID — номер кодовой страницы.
Для перекодировки на русский язык используется кодовая страница wCodePageID=1251 .

Для перекодировки русского текста, введенного в Win-коде также может использоваться функция

Getstdhandle c что это

GetStdHandle is a Windows API function. It is used to take a handle from a specific standard device (standard input, standard output or standard error) (to identify the value of a different device). Because many API functions require a handle, GetStdHandle is a very important function.

Function prototype

Included in the header file windows.h

parameter

The parameters of the GetStdHandle function can be one of the following

parameter meaning
STD_INPUT_HANDLE Standard input handle
STD_OUTPUT_HANDLE Standard output handle
STD_ERROR_HANDLE Standard error handler

Note: Only these three parameters are available. Different parameters are used to obtain handles for different standard devices.

return value

All know that the GetStdHandle function is used to get the handle, then its return value is of course a handle . This can also be seen from the function prototype.

Getstdhandle c что это

Функция GetStdHandle извлекает дескриптор для стандартного ввода данных, стандартного вывода или стандартной ошибки устройства.

HANDLE GetStdHandle(

DWORD nStdHandle // ввод, вывод или ошибка устройства

[in] Стандартное устройство, для которого дескриптор должен быть возвращен. Этот параметр может быть одним из следующих значений.

Дескриптор стандартного устройства ввода данных. Вначале, это — дескриптор консольного буфера ввода, CONIN $.

Дескриптор устройства стандартного вывода. Вначале, это — дескриптор активного экранного буфера консоли, CONOUT $.

Дескриптор стандартной ошибки устройства. Вначале, это — дескриптор активного экранного буфера консоли, CONOUT $.

Если функция завершается успешно, возвращаемое значение — дескриптор определяемого устройства. Дескриптор имеет права доступа GENERIC_READ и GENERIC_WRITE , если приложение не использовало функцию SetStdHandle , чтобы установить стандартный дескриптор с меньшими правами доступа.

Если функция завершается с ошибкой, возвращаемое значение — флажок INVALID_HANDLE_VALUE . Чтобы получить расширенные данные об ошибках, вызовите функцию GetLastError .

Дескрипторы, возвращенные функцией GetStdHandle, могут быть использованы прикладными программами, которым нужно читают из или записывать в консоль. Когда консоль создана, дескриптором стандартного ввода является дескриптор буфера ввода консоли, а стандартного вывода и обработки стандартной ошибки является дескриптор активного экранного буфера консоли. Эти дескрипторы могут быть использованы функциями ReadFile и WriteFile , или любой из консольных функций, которые обращаются к консольному буферу ввода или экранному буферу (например, функциям ReadConsoleInput , WriteConsole , или GetConsoleScreenBufferInfo ).

Стандартные дескрипторы процесса могут быть переназначен вызовом функции SetStdHandle , в этом случае функция GetStdHandle возвращает переназначенный дескриптор. Если стандартные дескрипторы были переназначены, Вы можете задать значение CONIN $ при вызове к функции CreateFile , чтобы получить дескриптор для буфера ввода консоли. Точно так же Вы можете задать значение CONOUT $, чтобы получить дескриптор для активного экранного буфера консоли.

Name already in use

Console-Docs / docs / getstdhandle.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Retrieves a handle to the specified standard device (standard input, standard output, or standard error).

nStdHandle [in]
The standard device. This parameter can be one of the following values.

Value Meaning
STD_INPUT_HANDLE ((DWORD)-10) The standard input device. Initially, this is the console input buffer, CONIN$ .
STD_OUTPUT_HANDLE ((DWORD)-11) The standard output device. Initially, this is the active console screen buffer, CONOUT$ .
STD_ERROR_HANDLE ((DWORD)-12) The standard error device. Initially, this is the active console screen buffer, CONOUT$ .

[!NOTE] The values for these constants are unsigned numbers, but are defined in the header files as a cast from a signed number and take advantage of the C compiler rolling them over to just under the maximum 32-bit value. When interfacing with these handles in a language that does not parse the headers and is re-defining the constants, please be aware of this constraint. As an example, ((DWORD)-10) is actually the unsigned number 4294967286 .

If the function succeeds, the return value is a handle to the specified device, or a redirected handle set by a previous call to SetStdHandle. The handle has GENERIC_READ and GENERIC_WRITE access rights, unless the application has used SetStdHandle to set a standard handle with lesser access.

[!TIP] It is not required to dispose of this handle with CloseHandle when done. See Remarks for more information.

If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

If an application does not have associated standard handles, such as a service running on an interactive desktop, and has not redirected them, the return value is NULL.

Handles returned by GetStdHandle can be used by applications that need to read from or write to the console. When a console is created, the standard input handle is a handle to the console’s input buffer, and the standard output and standard error handles are handles of the console’s active screen buffer. These handles can be used by the ReadFile and WriteFile functions, or by any of the console functions that access the console input buffer or a screen buffer (for example, the ReadConsoleInput, WriteConsole, or GetConsoleScreenBufferInfo functions).

The standard handles of a process may be redirected by a call to SetStdHandle, in which case GetStdHandle returns the redirected handle. If the standard handles have been redirected, you can specify the CONIN$ value in a call to the CreateFile function to get a handle to a console’s input buffer. Similarly, you can specify the CONOUT$ value to get a handle to a console’s active screen buffer.

The standard handles of a process on entry of the main method are dictated by the configuration of the /SUBSYSTEM flag passed to the linker when the application was built. Specifying /SUBSYSTEM:CONSOLE requests that the operating system fill the handles with a console session on startup, if the parent didn’t already fill the standard handle table by inheritance. On the contrary, /SUBSYSTEM:WINDOWS implies that the application does not need a console and will likely not be making use of the standard handles. More information on handle inheritance can be found in the documentation for STARTF_USESTDHANDLES.

Some applications operate outside the boundaries of their declared subsystem; for instance, a /SUBSYSTEM:WINDOWS application might check/use standard handles for logging or debugging purposes but operate normally with a graphical user interface. These applications will need to carefully probe the state of standard handles on startup and make use of AttachConsole, AllocConsole, and FreeConsole to add/remove a console if desired.

Some applications may also vary their behavior on the type of inherited handle. Disambiguating the type between console, pipe, file, and others can be performed with GetFileType.

It is not required to CloseHandle when done with the handle retrieved from GetStdHandle. The returned value is simply a copy of the value stored in the process table. The process itself is generally considered the owner of these handles and their lifetime. Each handle is placed in the table on creation depending on the inheritance and launch specifics of the CreateProcess call and will be freed when the process is destroyed.

Manual manipulation of the lifetime of these handles may be desirable for an application intentionally trying to replace them or block other parts of the process from using them. As a HANDLE can be cached by running code, that code will not necessarily pick up changes made via SetStdHandle. Closing the handle explicitly via CloseHandle will close it process-wide and the next usage of any cached reference will encounter an error.

Guidance for replacing a standard handle in the process table would be to get the existing HANDLE from the table with GetStdHandle, use SetStdHandle to place a new HANDLE in that is opened with CreateFile (or a similar function), then to close the retrieved handle.

There is no validation of the values stored as handles in the process table by either the GetStdHandle or SetStdHandle functions. Validation is performed at the time of the actual read/write operation such as ReadFile or WriteFile.

When attaching to a new console, standard handles are always replaced with console handles unless STARTF_USESTDHANDLES was specified during process creation.

If the existing value of the standard handle is NULL, or the existing value of the standard handle looks like a console pseudohandle, the handle is replaced with a console handle.

When a parent uses both CREATE_NEW_CONSOLE and STARTF_USESTDHANDLES to create a console process, standard handles will not be replaced unless the existing value of the standard handle is NULL or a console pseudohandle.

[!NOTE] Console processes must start with the standard handles filled or they will be filled automatically with appropriate handles to a new console. Graphical user interface (GUI) applications can be started without the standard handles and they will not be automatically filled.

Читать:
Smart survey gigabyte что это

Похожие статьи