Windows h c описание библиотеки документация

windows.h подробно, Русские Блоги, лучший сайт для обмена техническими статьями программиста.

ссылка
http://blog.csdn.net/fengningning/article/details/2306650?locationNum=1&fps=1
деконструкция windows.h

Комментарий в начале — это описание заголовочного файла:

/*++ BUILD Version: 0001    Increment this if a change has global effects

Copyright (c) 1985-1997, Microsoft Corporation

Module Name:


    windows.h

Abstract:

    Master include file for Windows applications.

--*/

Этот документ, похоже, не претерпел серьезных изменений и все еще является первой версией. «Увеличьте это значение, если изменение имеет глобальный эффект», что, вероятно, означает «если изменение имеет глобальный эффект, добавьте изменение в этот файл заголовка». В самих словах нет двусмысленности, но вы можете подумать, что если это я, я определенно не буду делать никаких заявлений об изменении этого файла — причина очень проста, это усложнит трансплантацию кода, и есть другие недостатки. фактор. Итак, это предложение, вероятно, то, что разработчики Microsoft сказали «себе». В абстрактной части написано: «Главный включаемый файл для приложений Windows», поэтому нет необходимости объяснять это.

#ifndef _WINDOWS_
#define _WINDOWS_

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

#ifndef WINVER
#define WINVER 0x0400
#else   
#if defined(_WIN32_WINNT) && (WINVER < 0x0400) && (_WIN32_WINNT > 0x0400)
#error WINVER setting conflicts with _WIN32_WINNT setting
#endif
#endif

Макрос WINVER связан с версией Windows, то есть, когда переменная макроса принимает разные значения, она соответствует разным версиям Windows. Соответствующие инструкции в документации Platform SDK следующие:

Windows Server 2003 WINVER>=0x0502
Windows XP WINVER>=0x0501
Windows 2000 WINVER>=0x0500
Windows NT 4.0 WINVER>=0x0400
Windows Me WINVER>=0x0500
Windows 98 WINVER>=0x0410
Windows 95 WINVER>=0x0400
(Как проверить номер версии моей операционной системы Windows? Один из способов представлен ниже: Вызов диспетчера задач -> Справка -> О диспетчере задач, сделайте то же самое в Windows XP Вы можете обнаружить, что номер версии — 5.1, в то время как это 5.2 в Windows server 2003 и 5.0 в Windows 2000. Ха-ха, действительно, это согласуется с описанием в документации Platform SDK!) Макрос _WIN32_WINNT на самом деле представляет номер версии. Следовательно, если вы определяете этот макрос одновременно, но он несовместим с определением WINVER, то компилятор выдаст ошибку «Настройка WINVER конфликтует с _WIN32_WINNT».

#if(WINVER >= 0x0500)
#pragma message ("")
#pragma message ("NOTE: WINVER has been defined as 0x0500 or greater which enables")
#pragma message ("Windows NT 5.0 and Windows 98 features. When these headers were released,")
#pragma message ("Windows NT 5.0 beta 1 and Windows 98 beta 2.1 were the current versions.")
#pragma message ("")
#pragma message ("For this release when WINVER is defined as 0x0500 or greater, you can only")
#pragma message ("build beta or test applications. To build a retail application,")
#pragma message ("set WINVER to 0x0400 or visit http://www.microsoft.com/msdn/sdk")
#pragma message ("to see if retail Windows NT 5.0 or Windows 98 headers are available.")
#pragma message ("")
#pragma message ("See the SDK release notes for more information.")
#pragma message ("")
#endif

Если заданный WINVER> = 0x0500, минимально необходимая версия Windows — Windows NT 5.0 (Windows 2000) и Windows 98. В это время компилятор выдаст серию сообщений, определенных с помощью #pragma message, в качестве приглашения при компиляции.

#ifndef _INC_WINDOWS
#define _INC_WINDOWS

#if defined (_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

/* If defined, the following flags inhibit definition
 *     of the indicated items.
 *
 * NOGDICAPMASKS     - CC_*, LC_*, PC_*, CP_*, TC_*, RC_
 * NOVIRTUALKEYCODES - VK_*
 * NOWINMESSAGES     - WM_*, EM_*, LB_*, CB_*
 *  NOWINSTYLES       - WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_*
 * NOSYSMETRICS      - SM_*
 * NOMENUS           - MF_*
 * NOICONS           - IDI_*
 * NOKEYSTATES       - MK_*
 * NOSYSCOMMANDS     - SC_*
 * NORASTEROPS       - Binary and Tertiary raster ops
 * NOSHOWWINDOW      - SW_*
 * OEMRESOURCE       - OEM Resource values
 * NOATOM            - Atom Manager routines
 * NOCLIPBOARD       - Clipboard routines
 * NOCOLOR           - Screen colors
 * NOCTLMGR          - Control and Dialog routines
 * NODRAWTEXT        - DrawText() and DT_*
 * NOGDI             - All GDI defines and routines
 * NOKERNEL          - All KERNEL defines and routines
 * NOUSER            - All USER defines and routines
 * NONLS             - All NLS defines and routines
 * NOMB              - MB_* and MessageBox()
 * NOMEMMGR          - GMEM_*, LMEM_*, GHND, LHND, associated routines
 * NOMETAFILE        - typedef METAFILEPICT
 * NOMINMAX          - Macros min(a,b) and max(a,b)
 * NOMSG             - typedef MSG and associated routines
 * NOOPENFILE        - OpenFile(), OemToAnsi, AnsiToOem, and OF_*
 * NOSCROLL          - SB_* and scrolling routines
 * NOSERVICE         - All Service Controller routines, SERVICE_ equates, etc.
 * NOSOUND           - Sound driver routines
 * NOTEXTMETRIC      - typedef TEXTMETRIC and associated routines
 * NOWH              - SetWindowsHook and WH_*
 * NOWINOFFSETS      - GWL_*, GCL_*, associated routines
 * NOCOMM            - COMM driver routines
 * NOKANJI           - Kanji support stuff.
 * NOHELP            - Help engine interface.
 * NOPROFILER        - Profiler interface.
 * NODEFERWINDOWPOS - DeferWindowPos routines
 * NOMCX             - Modem Configuration Extensions
 */

Весь следующий контент используется для определения некоторых других файлов заголовков, которые необходимо включить, и, конечно, также включается другая информация.
_MSC_VER Этот макрос определяет версию компилятора, связанная информация выглядит следующим образом:
C Compiler version 6.0 600
C/C++ compiler version 7.0 700
Visual C++, Windows, version 1.0 800
Visual C++, 32-bit, version 1.0 800
Visual C++, Windows, version 2.0 900
Visual C++, 32-bit, version 2.x 900
Visual C++, 32-bit, version 4.0 1000
Visual C++, 32-bit, version 5.0 1100
Visual C++, 32-bit, version 6.0 1200
Этот макрос должен быть определен, #pragma once указывает компилятору включать этот файл заголовка не более одного раза в процессе компиляции.
Что интересно, так это следующий большой комментарий, в котором объясняется, что когда макрос _MSC_VER определен и его номер версии> = 1020, то перечисленные рядом флаги не Можно определить.

#if defined(RC_INVOKED) && !defined(NOWINRES)

#include <winresrc.h>

#else

#if defined(RC_INVOKED)
/* Turn off a bunch of stuff to ensure that RC files compile OK. */
#define NOATOM
#define NOGDI
#define NOGDICAPMASKS
#define NOMETAFILE
#define NOMINMAX
#define NOMSG
#define NOOPENFILE
#define NORASTEROPS
#define NOSCROLL
#define NOSOUND
#define NOSYSMETRICS
#define NOTEXTMETRIC
#define NOWH
#define NOCOMM
#define NOKANJI
#define NOCRYPT
#define NOMCX
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_PPC_) && !defined(_ALPHA_) && !defined(_MIPS_) && !defined(_X86_) && defined(_M_IX86)
#define _X86_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_PPC_) && !defined(_ALPHA_) && !defined(_X86_) && !defined(_MIPS_) && defined(_M_MRX000)
#define _MIPS_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_PPC_) && !defined(_ALPHA_) && !defined(_X86_) && !defined(_MIPS_) && defined(_M_ALPHA)
#define _ALPHA_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_PPC_) && !defined(_ALPHA_) && !defined(_X86_) && !defined(_MIPS_) && defined(_M_PPC)
#define _PPC_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_PPC_) && !defined(_ALPHA_) && !defined(_X86_) && !defined(_MIPS_) && defined(_M_M68K)
#define _68K_
#endif

#if !defined(_68K_) && !defined(_MPPC_) && !defined(_PPC_) && !defined(_ALPHA_) && !defined(_X86_) && !defined(_MIPS_) && defined(_M_MPPC)
#define _MPPC_
#endif

#ifndef _MAC
#if defined(_68K_) || defined(_MPPC_)
#define _MAC
#endif
#endif

#ifndef RC_INVOKED
#if     ( _MSC_VER >= 800 )
#pragma warning(disable:4001)
#pragma warning(disable:4201)
#pragma warning(disable:4214)
#pragma warning(disable:4514)
#endif
#include <excpt.h>
#include <stdarg.h>
#endif /* RC_INVOKED */

Этот раздел немного длинный, но поскольку он интегрирован, его неизбежно анализировать вместе.
Макрос RC_INVOKED, кажется, является основой этого абзаца, поэтому начните с него. RC (компилятор ресурсов) определяет этот макрос, позволяя выборочно компилировать различные части файла заголовка ресурса. Зачем нужна такая необходимость? Когда вы думаете, использовать ли компилятор C или компилятор RC для компиляции файлов заголовков ресурсов, вы должны столкнуться с этой проблемой. Поскольку оператор определения, поддерживаемый RC, является только подмножеством компилятора C, если вы выбираете компиляцию с RC, вы должны быть осторожны, чтобы не записывать файлы заголовков ресурсов с синтаксисом, который RC не поддерживает.
Макрос NO_WINRES фактически определен в файле заголовка winresrc.h, а содержимое файла winresrc.h действительно очень мало:

#ifndef _WINRESRC_
#define _WINRESRC_

#include <winuser.rh>
#include <commctrl.rh>
#include <dde.rh>
#include <winnt.rh>
#include <dlgs.h>
#include <winver.h>

#endif

Ха-ха, прочитав, понять нетрудно.
Следующие определения # если! определено (68K) && !defined(MPPC) … связано с платформой.Так как большинство людей (включая меня) могут работать только на аппаратной платформе, такой как X86, эти определения не должны быть слишком небрежными.
Если RC_INVOKED не определен и _MSC_VER (номер версии компилятора)> = 800, то несколько предупреждений, связанных с версией компилятора, будут отключены. Если макрос RC_INVOKED не определен, необходимо включить два файла заголовков excpt.h и stdarg.h (excpt.h — это недокументированный файл заголовка, который содержит некоторые определения о SEH (структурированной обработке исключений); stdarg. h определяет макросы типа ANSI для функций с несколькими параметрами), так почему в этом случае должны быть включены эти два файла заголовков? Это объясняется в Platform SDK: «RC не поддерживает некоторые предопределенные макросы ANSI C-типа (например,DATE, FILE, LINE, STDC, TIME, TIMESTAMPEtc.) », а два заголовочных файла excpt.h и stdarg.h действительно определяют некоторые макросы ANSI-типа C. Поэтому, чтобы избежать ошибок компиляции, только когда RC не используется (то есть макрос RC_INVOKED не определен) Включайте только эти файлы заголовков.

#include <windef.h>
#include <winbase.h>
#include <wingdi.h>
#include <winuser.h>

Это самые важные и основные файлы заголовков, включенные в windows.h:
определение типа windef.h-basic
winbase.h — функция ядра
функция интерфейса устройства wingdi.h-graphics
winuser.h — функции пользовательского интерфейса

#ifdef _MAC
DECLARE_HANDLE(HKEY);
typedef HKEY *PHKEY;
#endif

Функции в windows.h:
СсылкаФункции windows.h

1. Получите текущий рабочий каталог

char* _getcwd( char *buffer, int maxlen );  
// Функция: Получить текущий рабочий каталог.  
// Заголовочный файл: #include <direct.h>  
// Возвращаемое значение: успешно возвращает указатель на буфер  
// Возвращаем NULL в случае ошибки и устанавливаем для errno одно из следующих трех значений:  
// У ENODEV нет такого устройства  
// ENOMEM недостаточно памяти  
// ERANGE результат вне допустимого диапазона  
// Примечание: когда первый параметр равен NULL, установка длины maxlen второго параметра недопустима, и функция  
// Используйте malloc для выделения достаточного количества памяти, вам нужно передать возвращаемое значение функции в функцию free () для  
// Освобождаем память. Если первый параметр не равен NULL, указанной maxlen длины недостаточно, и функция возвращает  
// Неправильно, установите для errno значение ERANGE  

2. Измените текущий рабочий каталог.

int _chdir( const char *dirname );  
// Функция: изменить текущий рабочий каталог.  
// Заголовочный файл: #include <direct.h>  
// Возвращаемое значение: возврат 0 в случае успеха  
// Возвращаем -1 в случае неудачи и устанавливаем errno следующим образом:  
// ENOENT Путь не существует  

3. Обход файла (поиск)

long _findfirst( char *filespec, struct _finddata_t *fileinfo );  
// Функция: предоставить первый файл, который в целом соответствует указанной записи в спецификации файлов. Функция _findnext обычно используется позже  
// Подсчитываем последующее использование для завершения обхода файла по определенной общей формуле.  
// Заголовочный файл: #include <io.h>  
// Параметр: спецификация файла-файла, может содержать подстановочные знаки  
// fileinfo-буфер информации о файле  
// Возвращаемое значение: единственный поисковый дескриптор возвращен успешно  
// Возвращаем -1 в случае ошибки и устанавливаем errno на следующее значение:  
// ENOENT этот универсальный шаблон не может быть сопоставлен  
// EINVAL недопустимое имя файла  
// Примечание: описание _finddata_t  

struct _finddata_t  
{  
    unsigned attrib;  
    time_t time_create;  
    time_t time_access;  
    time_t time_write;  
    _fsize_t size;  
    char name[_MAX_FNAME];  
};  
// среди них :    
// unsigned atrrib: место хранения атрибутов файла. Он хранит беззнаковый блок, используемый для представления файла  
// Атрибуты. Атрибуты файла представлены битами, в основном следующим образом: _A_ARCH (архив),  
// _A_HIDDEN (скрытый), _A_NORMAL (обычный), _A_RDONLY (только для чтения),  
// _A_SUBDIR (папка), _A_SYSTEM (система). Они находятся в <io.h>  
// Определенный макрос можно использовать напрямую, и его значение фактически является целым числом без знака  
// (Просто этот целочисленный тип должен быть степенью 2, чтобы гарантировать, что только один бит равен 1, а другой  
// бит равен 0). Поскольку это битовое представление, когда файл имеет несколько атрибутов, он часто  
// Получаем синтез нескольких атрибутов с помощью побитового ИЛИ. Например, только для чтения + скрытые + системные свойства,  
// Должно быть: _A_HIDDEN | _A_RDONLY | _A_SYSTEM.  
// time_t time_create: time_t здесь тип переменной, используемый для хранения времени создания файла.  
// time_t time_access: время последнего доступа к файлу.  
// time_t time_write: время последнего изменения файла.  
// _fsize_t size: размер файла. _Fsize_t здесь должен быть эквивалентен целому числу без знака, что означает  
// Количество байтов в файле.  
// имя символа [_MAX_FNAME]: имя файла для файла. Здесь _MAX_FNAME - постоянный макрос, который находится в заголовке <stdlib.h>  
// Определено в файле, это означает максимальную длину имени файла.  

int _findnext( long handle, struct _finddata_t *fileinfo );  
// Функция: в соответствии с общим правилом из предыдущего _findfirst найти следующий файл, который соответствует универсальному, и использовать его как основу  
// изменяем значение в fileinfo  
// Заголовочный файл: #include <io.h>  
// Параметр: длинный дескриптор поиска дескриптора (обычно возвращается _findfirst () непосредственно перед ним)  
// fileinfo-буфер информации о файле  
// Возвращаемое значение: возврат 0 в случае успеха  
// Возвращаем -1 в случае ошибки и устанавливаем errno на следующее значение:  
// ENOENT больше не имеет документов, соответствующих общему  

int _findclose( long handle );  
// Функция: закрыть дескриптор поиска и освободить соответствующие ресурсы  
// Заголовочный файл: #include <io.h>  
// Параметр: длинный дескриптор поиска (обычно возвращается _findfirst () непосредственно перед ним)  
// Возвращаемое значение: возврат 0 в случае успеха  
// Возвращаем -1 в случае ошибки и устанавливаем errno на следующее значение:  
// ENOENT больше не имеет документов, соответствующих общему  

4. Создайте каталог.

int _mkdir( const char *dirname );  
// Функция: Создать новый каталог, имя каталога - dirname.  
// Заголовочный файл: #include <direct.h>  
// Возвращаемое значение: возврат 0 в случае успеха  
// Возвращаем -1 в случае ошибки и устанавливаем для errno одно из следующих трех значений:  
// Разрешение EACCESS не разрешено  
// EEXIST Каталог уже существует  
// ENOENT нет такого файла или каталога  

5. Удалите каталог.

int _rmdir( const char *dirname );  
// Функция: удалить каталог с именем dirname.  
// Заголовочный файл: #include <direct.h>  
// Возвращаемое значение: возврат 0 в случае успеха  
// Возвращаем -1 в случае ошибки и устанавливаем для errno одно из следующих трех значений:  
// EACCESS: разрешение не разрешено  
// ENOTEMPTY: имя каталога не является папкой; или папка не пуста; или  
// где dirname - текущая рабочая папка; или dirname  
// как корневая папка;  
// ENOENT: нет такого файла или каталога  

6. Прочие операции

int _access( const char *path, int mode );  
// Функция: определение прав доступа к файлу / каталогу.  
// Заголовочный файл: #include <io.h>  
// Параметр: путь к файлу или каталогу  
// настройки режима-разрешения, значения следующие:  
//                   00 Existence only   
//                   02 Write permission   
//                   04 Read permission   
//                   06 Read and write permission  

int _chdrive( int drive );  
// Функция: изменить текущий рабочий диск.  
// Заголовочный файл: #include <direct.h>  
// Возвращаемое значение: возврат 0 в случае успеха  
// возвращаем -1 в случае неудачи  
// Примечание: описание параметра  
// drive = 1: Drive A  
// drive = 2: Drive B  
// диск = 3: диск C ...  

char* _getdcwd( int drive, char *buffer, int maxlen );  
// Функция: Получить текущий рабочий путь указанного диска.  
// Заголовочный файл: #include <direct.h>  
// Возвращаемое значение: успешно возвращает указатель на буфер  
// Возвращаем NULL в случае ошибки и устанавливаем для errno одно из следующих трех значений:  
// У ENODEV нет такого устройства  
// ENOMEM недостаточно памяти  
// ERANGE результат вне допустимого диапазона  
// Примечание: когда первый параметр равен NULL, эта функция устанавливает errno в ERANGE  

windows.h[edit | edit source]

The primary C header file for accessing the Win32 API is the <windows.h> header file. To make a Win32 executable, the first step is to include this header file in your source code. The windows.h header file should be included before any other library include, even the C standard library files such as stdio.h or stdlib.h. This is because the windows.h file includes macros and other components that may modify, extend, or replace things in these libraries. This is especially true when dealing with UNICODE, because windows.h will cause all the string functions to use UNICODE instead. Also, because many of the standard C library functions are already included in the Windows kernel, many of these functions will be available to the programmer without needing to load the standard libraries. For example, the function sprintf is included in windows.h automatically.

[edit | edit source]

There are a number of header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves, because of dependencies. The windows.h header file is actually a relatively small file, that provides conditional inclusion for a number of other header files, definitions of a few important macros, etc.


For a list of child header files visit———-

http://en.wikipedia.org/wiki/Windows.h

[edit | edit source]

This section will talk about some other interesting header files and libraries that can be included with your project, but which are not included by default with windows.h.

windows.h Macros[edit | edit source]

This section will briefly detail some of the changes that the user can make in the windows.h structure at compile time using macros.

WIN32_LEAN_AND_MEAN[edit | edit source]

The WIN32_LEAN_AND_MEAN macro causes several of the child headers to not be included in the build. This can help to speed up the compilation process.

UNICODE and _UNICODE[edit | edit source]

These macros, which we will discuss later, can generally be used interchangeably, but are frequently both defined together. These cause the program to be compiled with UTF-16 encoded strings instead of ASCII encoded strings. UTF-16 is one internationalized encoding based on the UNICODE standard and allows for more characters than the American ASCII encoding, although UTF-8 is often preferred in modern programming.

WINVER and _WIN32_WINNT[edit | edit source]

You must set these to a number greater or equal to 0x500 or you will not get some of the useful functions that are in Windows 2000 (and thus in any modern Windows) but were not in Windows 98.

Next Chapters[edit | edit source]

  • Handles and Data Types

From Wikipedia, the free encyclopedia

windows.h is a Windows-specific header file for the C and C++ programming languages which contains declarations for all of the functions in the Windows API, all the common macros used by Windows programmers, and all the data types used by the various functions and subsystems. It defines a very large number of Windows specific functions that can be used in C. The Win32 API can be added to a C programming project by including the <windows.h> header file and linking to the appropriate libraries. To use functions in xxxx.dll, the program must be linked to xxxx.lib (or libxxxx.dll.a in MinGW). Some headers are not associated with a .dll but with a static library (e.g. scrnsave.h needs scrnsave.lib).

[edit]

There are a number of child header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies.

windows.h may include any of the following header files:

  • stdarg.h – variable-argument functions (standard C header)
  • windef.h – various macros and types
  • winnt.h – various macros and types (for Windows NT) [1]
  • basetsd.h – various types [2]
  • guiddef.h – the GUID type [3]
  • ctype.h – character classification (standard C header)
  • string.h – strings and buffers (standard C header)
  • winbase.h – kernel32.dll: kernel services; advapi32.dll:kernel services(e.g. CreateProcessAsUser function), access control(e.g. AdjustTokenGroups function).
  • winerror.h – Windows error codes [4]
  • wingdi.h – GDI (Graphics Device Interface) [5]
  • winuser.h – user32.dll: user services, inline resource macro(e.g. MAKEINTRESOURCE macro [6]), inline dialog macro(e.g. DialogBox function [7]). [8]
  • winnls.h – NLS (Native Language Support)
  • wincon.h – console services
  • winver.h – version information [9]
  • winreg.h – Windows registry [10]
  • winnetwk.h – WNet (Windows Networking) [11]
  • winsvc.h – Windows services and the SCM (Service Control Manager)
  • imm.h – IME (Input Method Editor)

[edit]

  • cderr.h – CommDlgExtendedError function error codes
  • commdlg.h – Common Dialog Boxes
  • dde.h – DDE (Dynamic Data Exchange)
  • ddeml.h – DDE Management Library
  • dlgs.h – various constants for Common Dialog Boxes
  • lzexpand.h – LZ (Lempel-Ziv) compression/decompression
  • mmsystem.h – Windows Multimedia
  • nb30.h – NetBIOS
  • rpc.h – RPC (Remote procedure call)
  • shellapi.h – Windows Shell API
  • wincrypt.h – Cryptographic API
  • winperf.h – Performance monitoring
  • winresrc.h – used in resources
  • winsock.h – Winsock (Windows Sockets), version 1.1
  • winspool.h – Print Spooler
  • winbgim.h – Standard graphics library

OLE and COM[edit]

  • ole2.h – OLE (Object Linking and Embedding)
  • objbase.h – COM (Component Object Model)
  • oleauto.h – OLE Automation
  • olectlid.h – various GUID definitions

Macros[edit]

Several macros affect the behavior of windows.h.

  • UNICODE – when defined, this causes TCHAR to be a synonym of WCHAR instead of CHAR[12], and all type-generic API functions and messages that work with text will be defined to the -W versions instead of the -A versions. (It is similar to the windows C runtime’s _UNICODE macro.)
  • RC_INVOKED – defined when the resource compiler (RC.EXE) is in use instead of a C compiler.
  • WINVER – used to enable features only available in newer operating systems. Define it to 0x0501 for Windows XP, and 0x0600 for Windows Vista.
  • WIN32_LEAN_AND_MEAN – used to reduce the size of the header files and speed up compilation. Excludes things like cryptography, DDE, RPC, the Windows Shell and Winsock.

See also[edit]

  • Windows.pas

From Wikipedia, the free encyclopedia

windows.h is a Windows-specific header file for the C and C++ programming languages which contains declarations for all of the functions in the Windows API, all the common macros used by Windows programmers, and all the data types used by the various functions and subsystems. It defines a very large number of Windows specific functions that can be used in C. The Win32 API can be added to a C programming project by including the <windows.h> header file and linking to the appropriate libraries. To use functions in xxxx.dll, the program must be linked to xxxx.lib (or libxxxx.dll.a in MinGW). Some headers are not associated with a .dll but with a static library (e.g. scrnsave.h needs scrnsave.lib).

[edit]

There are a number of child header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies.

windows.h may include any of the following header files:

  • stdarg.h – variable-argument functions (standard C header)
  • windef.h – various macros and types
  • winnt.h – various macros and types (for Windows NT) [1]
  • basetsd.h – various types [2]
  • guiddef.h – the GUID type [3]
  • ctype.h – character classification (standard C header)
  • string.h – strings and buffers (standard C header)
  • winbase.h – kernel32.dll: kernel services; advapi32.dll:kernel services(e.g. CreateProcessAsUser function), access control(e.g. AdjustTokenGroups function).
  • winerror.h – Windows error codes [4]
  • wingdi.h – GDI (Graphics Device Interface) [5]
  • winuser.h – user32.dll: user services, inline resource macro(e.g. MAKEINTRESOURCE macro [6]), inline dialog macro(e.g. DialogBox function [7]). [8]
  • winnls.h – NLS (Native Language Support)
  • wincon.h – console services
  • winver.h – version information [9]
  • winreg.h – Windows registry [10]
  • winnetwk.h – WNet (Windows Networking) [11]
  • winsvc.h – Windows services and the SCM (Service Control Manager)
  • imm.h – IME (Input Method Editor)

[edit]

  • cderr.h – CommDlgExtendedError function error codes
  • commdlg.h – Common Dialog Boxes
  • dde.h – DDE (Dynamic Data Exchange)
  • ddeml.h – DDE Management Library
  • dlgs.h – various constants for Common Dialog Boxes
  • lzexpand.h – LZ (Lempel-Ziv) compression/decompression
  • mmsystem.h – Windows Multimedia
  • nb30.h – NetBIOS
  • rpc.h – RPC (Remote procedure call)
  • shellapi.h – Windows Shell API
  • wincrypt.h – Cryptographic API
  • winperf.h – Performance monitoring
  • winresrc.h – used in resources
  • winsock.h – Winsock (Windows Sockets), version 1.1
  • winspool.h – Print Spooler
  • winbgim.h – Standard graphics library

OLE and COM[edit]

  • ole2.h – OLE (Object Linking and Embedding)
  • objbase.h – COM (Component Object Model)
  • oleauto.h – OLE Automation
  • olectlid.h – various GUID definitions

Macros[edit]

Several macros affect the behavior of windows.h.

  • UNICODE – when defined, this causes TCHAR to be a synonym of WCHAR instead of CHAR[12], and all type-generic API functions and messages that work with text will be defined to the -W versions instead of the -A versions. (It is similar to the windows C runtime’s _UNICODE macro.)
  • RC_INVOKED – defined when the resource compiler (RC.EXE) is in use instead of a C compiler.
  • WINVER – used to enable features only available in newer operating systems. Define it to 0x0501 for Windows XP, and 0x0600 for Windows Vista.
  • WIN32_LEAN_AND_MEAN – used to reduce the size of the header files and speed up compilation. Excludes things like cryptography, DDE, RPC, the Windows Shell and Winsock.

See also[edit]

  • Windows.pas

windows.h является Windows-конкретный файл заголовков для языка C программирования, который содержит заявления для всех функций в Windows API, все общие макросы, которые используются программистами окон, и все типы данных, используемых различными функциями и подсистем. Он определяет большое количество окон конкретные функции, которые могут быть использованы в С. Win32 API могут быть добавлены в проект программирования C, включив <windows.h> заголовка файла и ссылки на соответствующие библиотеки. Для использования функции в XXXX. DLL, программа должна быть увязана с XXXX. Lib (или Lib XXXX. В MinGW). Некоторые заголовки не связаны с расширением. DLL, но при статической библиотеки (например, scrnsave.h scrnsave.lib потребности).

Есть несколько файлов ребенка заголовок, который автоматически входит в windows.h. Многие из этих файлов не может быть просто включен сами по себе, из-за зависимостей.

windows.h может включать любую из следующих файлов заголовок:
excpt.h — Обработка исключений
stdarg.h — переменная аргумент функции (стандартный заголовок C)
windef.h — различные макросы и типы
winnt.h — различные макросы и типы (для Windows NT)
basetsd.h — различные типы
guiddef.h — тип GUID
ctype.h — характер классификации (стандартный заголовок C)
string.h — строк и буферов (стандартный заголовок C)
winbase.h — Kernel32.dll: ядро услуги
Winerror.h — коды ошибок Windows
WINGDI.H — GDI (Graphics Device Interface)
WINUSER.H — user32.dll: пользователь услугами
winnls.h — NLS (Native Language Support)
wincon.h — консоль услуги
winver.h — информация о версии
winreg.h — реестр Windows
winnetwk.h — Wnet (Windows Networking)
Winsvc.h — Windows Services и SCM (Service Control Manager)
imm.h — IME (редактор метода ввода)

Дополнительная включает в себя:
cderr.h — CommDlgExtendedError кодов функция ошибок
commdlg.h — общих диалоговых окон
dde.h — DDE (Dynamic Data Exchange)
ddeml.h — DDE Управление библиотека
dlgs.h — различные константы для общих диалоговых окон
lzexpand.h — LZ (Зив-Зива) компрессии / декомпрессии
mmsystem.h — Windows Multimedia
nb30.h — NetBIOS
rpc.h — RPC (Remote Procedure Call)
shellapi.h — оболочки Windows API
wincrypt.h — Cryptographic API
winperf.h — мониторинг эффективности
winresrc.h — используется в ресурсах
winsock.h — Winsock (Windows Sockets), версия 1.1
winsock2.h — Winsock (Windows Sockets), версия 2
winspool.h — Диспетчер очереди печати

OLE и COM:
ole2.h — OLE (Object Linking и вложение)
objbase.h — COM (Component Object Model)
oleauto.h — OLE Automation
olectlid.h — различные GUID определений
[Править] Макросы

Несколько макросов влияют на поведение windows.h.
UNICODE — определить, когда это приводит к TCHAR быть синонимом WCHAR вместо CHAR, и все тип-родовых функций API и сообщений, работа с текстом будет определен-З версиях вместо-версии. (Это похоже на Windows _UNICODE макроса C Runtime’s.)
RC_INVOKED — определить, когда ресурс компилятора (Rc.exe) используется вместо компилятора C.
WINVER — используется для включения функций доступны только в более новых операционных систем. Определить ее 0x0501 для Windows XP, и 0x0600 для Windows Vista.
WIN32_LEAN_AND_MEAN — используется для уменьшения размера файлов заголовков и ускорить компиляцию. За исключением вещей, как криптография, DDE, RPC, Windows Shell и Winsock.

Windows.h

windows.h — это файл заголовка Windows для языков программирования C и C++, который содержит описания для всех функций в Windows API, все распространенные макросы, используемые программистами Windows, и все типы данных, используемые различными функциями и подмножествами. Он определяет очень большое количество специфичных для Windows функций, которые могут использоваться в C. Win32 API можно добавить в проект программирования C, включив файл заголовка & lt; windows.h & gt; и связав его с соответствующими библиотеками. Для использования функций в xxxx.dll программа должна быть связана с xxxx.lib (или libxxxx.dll.a в MinGW). Некоторые заголовки связаны не с библиотекой .dll, а с библиотекой c (например, scrnsave.h требуется scrnsave.lib).

Дочерние файлы заголовка

Существует несколько дочерних файлов заголовка, которые автоматически включаются в файл windows.h. Многие из этих файлов не могут быть просто включены сами по себе (они не являются автономными) из-за зависимостей.

windows.h может включать любой из следующих файлов заголовка:

  • excpt.h — Обработка исключений
  • stdarg.h — функции переменного аргумента (стандартный заголовок C)
  • windef.h — различные макросы и типы
  • t.h — различные макросы и типы (для Windows NT)
  • basetsd.h — различные типы
  • guiddef.h — тип
  • ctype.h — классификация символов (стандартный заголовок C)
  • string.h — строки и буферы (стандартный заголовок C)
  • winbase.h — kernel32.dll: kernel services; advapi32.dll: kernel services (например, функция CreateProcessAsUser), управление доступом (например, функция AdjustTokenGroups).
  • winerror.h — Коды ошибок Windows
  • wingdi.h — GDI (интерфейс графического устройства)
  • winuser.h — user32.dll: пользовательские службы
  • ls.h — NLS (поддержка родного языка)
  • wincon.h — консольные услуги
  • winver.h — информация о версии
  • winreg.h — реестр Windows
  • etwk.h — WNet (Windows Networking)
  • winsvc.h — службы Windows и SCM (Service Control Manager)
  • imm.h — IME (редактор методов ввода)

Дополнительно включает

  • cderr.h — коды ошибок функции
  • commdlg.h — общие диалоговые окна
  • dd.h — DDE (динамический обмен данными)
  • ddeml.h — Библиотека управления DDE
  • dlgs.h — различные константы для общих диалоговых окон
  • lzexpand.h — LZ (Lempel-Av) сжатие/декомпрессия
  • mssystem.h — Windows Multimedia
  • nb30.h — NetBIOS
  • rpc.h — RPC (удаленный вызов процедуры)
  • shellapi.h — Windows Shell API
  • wincrypt.h — Cryptographic API
  • winperf.h — Мониторинг производительности
  • winresrc.h — используется в ресурсах
  • winso .h — Winsock (Windows So ets), версия № 1
  • winspool.h — Печатное устройство
  • winbgim.h — Стандартная графическая библиотека

OLE и COM

  • ole2.h — OLE (связывание и встраивание объектов)
  • objbase.h — COM (объектная модель компонента)
  • oleut h — автоматизация OLE
  • olectlid.h — различные определения GUID

Мак

Несколько макросов влияют на поведение windows.h.

  • UNICODE — если он определен, то TCHAR будет синонимом WCHAR вместо CHAR, а все универсальные функции API и сообщения, которые работают с текстом, будут определены в версиях -W, а не в версиях -A. (Он похож на windows C runtime’s _ UNICODE macro.)
  • RC _ INVOKED — определяется, когда используется компонент ресурсов (RC.EXE), а не компонент C.
  • WINVER — используется для включения функций, доступных только в новых операционных системах. Определите значение 0x0501 для Windows XP и 0x0600 для Windows Vista.
  • WIN32 _ LEAN _ AND _ MEAN — используется для уменьшения размера файлов заголовка и ускорения компиляции. такие вещи, как криптография, DDE, RPC, Windows Shell и Winsock.

См. также

  • Windows.pas

#include <winapifamily.h> /*++ BUILD Version: 0001 Increment this if a change has global effects Copyright (c) Microsoft Corporation. All rights reserved. Module Name: windows.h Abstract: Master include file for Windows applications. */ #ifndef _WINDOWS_ #define _WINDOWS_ #include <sdkddkver.h> #ifndef _INC_WINDOWS #define _INC_WINDOWS #if defined (_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #pragma region Application Family or OneCore Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM) /* If defined, the following flags inhibit definition * of the indicated items. * * NOGDICAPMASKS — CC_*, LC_*, PC_*, CP_*, TC_*, RC_ * NOVIRTUALKEYCODES — VK_* * NOWINMESSAGES — WM_*, EM_*, LB_*, CB_* * NOWINSTYLES — WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_* * NOSYSMETRICS — SM_* * NOMENUS — MF_* * NOICONS — IDI_* * NOKEYSTATES — MK_* * NOSYSCOMMANDS — SC_* * NORASTEROPS — Binary and Tertiary raster ops * NOSHOWWINDOW — SW_* * OEMRESOURCE — OEM Resource values * NOATOM — Atom Manager routines * NOCLIPBOARD — Clipboard routines * NOCOLOR — Screen colors * NOCTLMGR — Control and Dialog routines * NODRAWTEXT — DrawText() and DT_* * NOGDI — All GDI defines and routines * NOKERNEL — All KERNEL defines and routines * NOUSER — All USER defines and routines * NONLS — All NLS defines and routines * NOMB — MB_* and MessageBox() * NOMEMMGR — GMEM_*, LMEM_*, GHND, LHND, associated routines * NOMETAFILE — typedef METAFILEPICT * NOMINMAX — Macros min(a,b) and max(a,b) * NOMSG — typedef MSG and associated routines * NOOPENFILE — OpenFile(), OemToAnsi, AnsiToOem, and OF_* * NOSCROLL — SB_* and scrolling routines * NOSERVICE — All Service Controller routines, SERVICE_ equates, etc. * NOSOUND — Sound driver routines * NOTEXTMETRIC — typedef TEXTMETRIC and associated routines * NOWH — SetWindowsHook and WH_* * NOWINOFFSETS — GWL_*, GCL_*, associated routines * NOCOMM — COMM driver routines * NOKANJI — Kanji support stuff. * NOHELP — Help engine interface. * NOPROFILER — Profiler interface. * NODEFERWINDOWPOS — DeferWindowPos routines * NOMCX — Modem Configuration Extensions */ #if defined(RC_INVOKED) && !defined(NOWINRES) #include <winresrc.h> #else #if defined(RC_INVOKED) /* Turn off a bunch of stuff to ensure that RC files compile OK. */ #define NOATOM #define NOGDI #define NOGDICAPMASKS #define NOMETAFILE #define NOMINMAX #define NOMSG #define NOOPENFILE #define NORASTEROPS #define NOSCROLL #define NOSOUND #define NOSYSMETRICS #define NOTEXTMETRIC #define NOWH #define NOCOMM #define NOKANJI #define NOCRYPT #define NOMCX #endif #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_IX86) #define _X86_ #endif #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_AMD64) #define _AMD64_ #endif #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_ARM) #define _ARM_ #endif #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_ARM64) #define _ARM64_ #endif #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_M68K) #define _68K_ #endif #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_MPPC) #define _MPPC_ #endif #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_M_IX86) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && defined(_M_IA64) #if !defined(_IA64_) #define _IA64_ #endif /* !_IA64_ */ #endif #ifndef _MAC #if defined(_68K_) || defined(_MPPC_) #define _MAC #endif #endif #if defined (_MSC_VER) #if ( _MSC_VER >= 800 ) #ifndef __cplusplus #pragma warning(disable:4116) /* TYPE_ALIGNMENT generates this — move it */ /* outside the warning push/pop scope. */ #endif #endif #endif #ifndef RC_INVOKED #if ( _MSC_VER >= 800 ) #pragma warning(disable:4514) #ifndef __WINDOWS_DONT_DISABLE_PRAGMA_PACK_WARNING__ #pragma warning(disable:4103) #endif #if _MSC_VER >= 1200 #pragma warning(push) #endif #pragma warning(disable:4001) #pragma warning(disable:4201) #pragma warning(disable:4214) #endif #include <excpt.h> #include <stdarg.h> #endif /* RC_INVOKED */ #include <windef.h> #include <winbase.h> #include <wingdi.h> #include <winuser.h> #if !defined(_MAC) || defined(_WIN32NLS) #include <winnls.h> #endif #ifndef _MAC #include <wincon.h> #include <winver.h> #endif #if !defined(_MAC) || defined(_WIN32REG) #include <winreg.h> #endif #ifndef _MAC #include <winnetwk.h> #endif #ifndef WIN32_LEAN_AND_MEAN #include <cderr.h> #include <dde.h> #include <ddeml.h> #include <dlgs.h> #ifndef _MAC #include <lzexpand.h> #include <mmsystem.h> #include <nb30.h> #include <rpc.h> #endif #include <shellapi.h> #ifndef _MAC #include <winperf.h> #include <winsock.h> #endif #ifndef NOCRYPT #include <wincrypt.h> #include <winefs.h> #include <winscard.h> #endif #ifndef NOGDI #ifndef _MAC #include <winspool.h> #ifdef INC_OLE1 #include <ole.h> #else #include <ole2.h> #endif /* !INC_OLE1 */ #endif /* !MAC */ #include <commdlg.h> #endif /* !NOGDI */ #endif /* WIN32_LEAN_AND_MEAN */ #include <stralign.h> #ifdef _MAC #include <winwlm.h> #endif #ifdef INC_OLE2 #include <ole2.h> #endif /* INC_OLE2 */ #ifndef _MAC #ifndef NOSERVICE #include <winsvc.h> #endif #if(WINVER >= 0x0400) #ifndef NOMCX #include <mcx.h> #endif /* NOMCX */ #ifndef NOIME #include <imm.h> #endif #endif /* WINVER >= 0x0400 */ #endif #ifndef RC_INVOKED #if ( _MSC_VER >= 800 ) #if _MSC_VER >= 1200 #pragma warning(pop) #else #pragma warning(default:4001) #pragma warning(default:4201) #pragma warning(default:4214) /* Leave 4514 disabled. It’s an unneeded warning anyway. */ #endif #endif #endif /* RC_INVOKED */ #endif /* RC_INVOKED */ #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM) */ #pragma endregion #endif /* _INC_WINDOWS */ #endif /* _WINDOWS_ */

Понравилась статья? Поделить с друзьями:
  • Windows h c графика в консоли функции
  • Windows install python for all users
  • Windows graphics programming win32 gdi and directdraw
  • Windows install programs from command line
  • Windows git скачать через командную строку