Registry

The registry is a system-defined database in which applications and system components store and retrieve configuration data.

The registry was first included as part of Microsoft® Windows® 3.1 to address problems inherent in the system configuration storage mechanism of earlier versions of Windows. Before Windows 3.1, the Windows operating system used Win.ini and System.ini files for this purpose. In addition, applications could create and maintain their own .ini files. All .ini files were ASCII text files, which anyone could read and edit.

Some of the most important problems with storing system information in .ini files are the following:

  • The fact that anyone could access and change these files meant that the integrity of the information contained in the files could not be guaranteed.
  • No rules governed what could be added to an .ini file or where it could be located, so it was hard to find or change an item. This is also related to the first problem: if someone edited an .ini file, an application not capable of dealing with edited .ini files would not be able to retrieve the necessary configuration information.
  • Each .ini file was strictly limited in size to 64 KB. One solution was to have private .ini files, but this caused problems with sharing data for applications that were using dynamic data exchange (DDE) or OLE.

The registry database included with Windows 3.1 is the basis of the registry now implemented in both Microsoft® Windows NT® and Windows 95.

  • About the Registry
  • Using the Registry
  • Registry Reference
Microsoft Platform SDK, February 2001 Edition.
This content last built on Thursday, February 01, 2001.


About the Registry

The registry stores data in binary files. To manipulate registry data, an application must use the registry functions or a utility called the Registry Editor (Regedit.exe). You can use the Registry Editor to make manual changes to the registry.

This overview describes the registry and the functions you can call to access and manipulate the data stored there. The data stored in the registry varies according to the platform that is used. This overview contains a description of registry entries that can exist on any platform.

  • Structure of the Registry
  • Registry Storage Space
  • Predefined Keys
  • Registry Hives
  • The HKEY_CLASSES_ROOT Key
  • Categories of Data
  • Opening, Creating, and Closing Keys
  • Writing and Deleting Registry Data
  • Retrieving Data from the Registry
  • Registry Files
  • Registry Key Security and Access Rights


Structure of the Registry

The registry stores data in a hierarchically structured tree. Each node in the tree is called a key. Each key can contain both subkeys and data entries called values. Sometimes, the presence of a key is all the data that an application requires; other times, an application opens a key and uses the values associated with the key. A key can have any number of values, and the values can be in any form. Registry values can be any of the following types:

Type | Description
REG_BINARY | Raw binary data in any form.
REG_DWORD | A 32-bit number.
REG_SZ | A null-terminated string. It is a Unicode or ANSI string, depending on whether you use the Unicode or ANSI function.
REG_MULTI_SZ | An array of null-terminated strings, terminated by two null characters.
REG_EXPAND_SZ | A null-terminated string that contains unexpanded references to environment variables (for example, "%PATH%"). It is a Unicode or ANSI string, depending on whether you use the Unicode or ANSI function.
REG_LINK | A Unicode symbolic link.
REG_NONE | No defined value type.

Each key has a name consisting of one or more printable characters. Key names cannot include a backslash (\), but any other printable or unprintable character can be used. The name of each subkey is unique with respect to the key that is immediately above it in the hierarchy. Key names are not localized into other languages, although values may be.

The maximum length of a key name is 512 ANSI characters or 256 Unicode characters. The maximum length of a key value is 32767 ANSI characters or 16383 Unicode characters.

The following figure is an example registry key structure as displayed by the Registry Editor.

Each of the HKEY trees is a key. HARDWARE, SAM, SECURITY, SOFTWARE, and SYSTEM are subkeys of HKEY_LOCAL_MACHINE and DESCRIPTION, DEVICEMAP, and RESOURCEMAP are subkeys of HARDWARE key in the preceding figure. Each value consists of a value name and its associated data, if any. MaxObjectNumber and VgaCompatible are values under the DEVICEMAP subkey containing data.


Registry Storage Space

Although there are few technical limits to the type and size of data an application can store in the registry, certain practical guidelines exist to promote system efficiency. An application should store configuration and initialization data in the registry, but other kinds of data should be stored elsewhere.

Generally, data consisting of more than one or two kilobytes (K) should be stored as a file and referred to by using a key in the registry rather than being stored as a value. Instead of duplicating large pieces of data in the registry, an application should save the data as a file and refer to the file. Executable binary code should never be stored in the registry.

A value entry uses much less registry space than a key. To save space, an application should group similar data together as a structure and store the structure as a value rather than storing each of the structure members as a separate key. (Storing the data in binary form allows an application to store data in one value that would otherwise be made up of several incompatible types.)

You can also specify the size of the registry in the paged pool. For more information on how to do this, refer to Viewing and Setting the Registry Size Limit (RSL).


Viewing and Setting the Registry Size Limit (RSL)

Registry data is stored in the paged pool, an area of physical memory used for system data that can be written to disk when not in use. The RegistrySizeLimit registry key value establishes the maximum amount of paged pool space—and, because it is the same size as the maximum paged pool space, the disk paging file space—that can be consumed by registry data from all applications. It is designed to prevent the registry from consuming space needed by processes. This value does not allocate space in the paged pool, nor does it assure that the space will be available if needed.

The hive location of RegistrySizeLimit is HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control. The value of RegistrySizeLimit is of the type REG_DWORD and has a data length of 4 bytes. If you attempt to set the value of RegistrySizeLimit to another type or data length, the value will remain unchanged. The value of RegistrySizeLimit is not set by default; use the Registry Editor to set the value.

The paged pool size is determined by the PagedPoolSize registry key value, which is located in the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Memory Management subkey. When the paged pool size changes, either because the Windows operating system adjusts it or an administrator changes it, the value of RegistrySizeLimit changes also. The default size of the paged pool is 32 MB, so the RegistrySizeLimit value is 8 MB.

The system ensures that the minimum value of RegistrySizeLimit is 4 MB and the maximum is approximately 80 percent of the PagedPoolSize value. Thus, the size of the paged pool is limited to 128 MB, and the RegistrySizeLimit value cannot exceed 102 MB, or 80 percent of 128 MB.

If the value of RegistrySizeLimit is 0, or if the entry doesn't exist in the registry, the system dynamically adjusts the maximum size of the registry according to the size of the paged pool. If the value of this entry is greater than 16 MB and less than or equal to 80 percent of the paged pool size, the value will be used as the maximum size of the registry size. The system will not calculate an optimal maximum size or adjust the maximum size when the amount of memory or the size of the paged pool changes. If the value of this entry is greater than 80 percent of the size of the paged pool, the system sets the maximum size of the registry to 80 percent of the size of the paged pool.

In addition, if the value of PagedPoolSize is 0, the system calculates an optimal value for both RegistrySizeLimit and PagedPoolSize. For most purposes, this is a good default value for PagedPoolSize, unless your server has less than 256 MB of memory. Typically, the system sets the size of the paged pool approximately equal to the amount of physical memory on the computer, and sets the maximum size of the registry to approximately 33 percent of the value of PagedPoolSize.

The space controlled by RegistrySizeLimit includes the hive space, as well as some of the registry's run-time structures. Other run-time structures in the registry are protected by their own size limits or by other means.

To ensure that a user can always start the system and edit the registry, the registry is not subject to the value set in RegistrySizeLimit until after the first successful loading of a hive—that is, the loading of a user profile.

For more information on RegistrySizeLimit and PagedPoolSize, refer to the registry help file, Regentry.chm, in the Windows NT Resource Kit.


Predefined Keys

An application must open a key before it can add data to the registry. To open a key, an application must supply a handle to another key in the registry that is already open. The system defines standard handles that are always open. An application can use these predefined handles as entry points to the registry.

The system provides two predefined keys at the root of the registry: HKEY_LOCAL_MACHINE and HKEY_USERS. In addition, the system defines HKEY_CURRENT_CONFIG (a subkey of HKEY_LOCAL_MACHINE), HKEY_CURRENT_USER (a subkey of HKEY_USERS), and HKEY_CLASSES_ROOT (a subkey that merges information from HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER). These registry handles are valid for all Windows implementations of the registry, although the use of the handles may vary from platform to platform. In addition, other predefined handles have been defined for specific platforms.

Predefined keys help an application navigate in the registry and make it possible to develop tools that allow a system administrator to manipulate categories of data. Applications that add data to the registry should always work within the framework of predefined keys, so administrative tools can find and use the new data.

The RegOverridePredefKey function enables you to map a predefined registry key to a specified key in the registry. For instance, a software installation program could remap a predefined key before installing a DLL component. This enables the installation program to easily examine the information that the DLL's installation procedure writes to the predefined key. The following predefined keys are used as entry points to the registry.

Entry point | Use
HKEY_CLASSES_ROOT | Registry entries subordinate to this key define types (or classes) of documents and the properties associated with those types. Shell and COM applications use the information stored under this key. This key also provides backward compatibility with the Windows 3.1 registration database by storing information for DDE and OLE support. File viewers and user interface extensions store their OLE class identifiers in HKEY_CLASSES_ROOT, and in-process servers are registered in this key.
HKEY_CURRENT_CONFIG | Contains information about the current hardware profile of the local computer system. The information under HKEY_CURRENT_CONFIG describes only the differences between the current hardware configuration and the standard configuration. Information about the standard hardware configuration is stored under the Software and System keys of HKEY_LOCAL_MACHINE. HKEY_CURRENT_CONFIG is an alias for HKEY_LOCAL_MACHINE\System\CurrentControlSet\Hardware Profiles\Current. This key was introduced in Windows 95 and Windows NT version 4.0.
HKEY_CURRENT_USER | Registry entries subordinate to this key define the preferences of the current user. These preferences include the settings of environment variables, data about program groups, colors, printers, network connections, and application preferences. This key makes it easier to establish the current user's settings; the key maps to the current user's branch in HKEY_USERS. In HKEY_CURRENT_USER, software vendors store the current user-specific preferences to be used within their applications. Microsoft, for example, creates the HKEY_CURRENT_USER\Software\Microsoft key for its applications to use, with each application creating its own subkey under the Microsoft key.
HKEY_DYN_DATA | Windows 95/98/Me: Registry entries subordinate to this key allow you to collect performance data.
HKEY_LOCAL_MACHINE | Registry entries subordinate to this key define the physical state of the computer, including data about the bus type, system memory, and installed hardware and software. It contains subkeys that hold current configuration data, including Plug and Play information (the Enum branch, which includes a complete list of all hardware that has ever been on the system), network logon preferences, network security information, software-related information (such as server names and the location of the server), and other system information.
HKEY_PERFORMANCE_DATA | Windows NT/2000 or later: Registry entries subordinate to this key allow you to access performance data. The data is not actually stored in the registry; the registry functions cause the system to collect the data from its source.
HKEY_USERS | Registry entries subordinate to this key define the default user configuration for new users on the local computer and the user configuration for the current user. Because Windows 95/98 also supports HKEY_CURRENT_USER, applications can access the user-specific information the same way they do under Windows NT.


Registry Hives

A hive is a group of keys, subkeys, and values in the registry that has a set of supporting files containing backups of the data in the hive. The setup phase of the Windows NT/Windows 2000 boot process automatically retrieves data from these supporting files. You can also retrieve data manually using the Import Registry File menu item of the Registry Editor (Regedit.exe). When you shut down Windows NT or Windows 2000, the operating system automatically writes the hive data to the supporting files. You can also back up the hive data manually using the Export Registry File menu item of the Registry Editor.

The supporting files for all hives except HKEY_CURRENT_USER are in the Systemroot\System32\Config directory; the supporting files for HKEY_CURRENT_USER are in the Systemroot\Profiles\Username directory. The file name extensions of the files in these directories, and in some cases a lack of an extension, indicate the type of data they contain. The following table lists these extensions along with a description of the data in the file.

File name extension | Description of the data
No extension | A complete copy of the hive data.
.alt | A backup copy of the critical HKEY_LOCAL_MACHINE\System hive. Only the System key has an .alt file.
.log | A transaction log of changes to the keys and value entries in the hive.
.sav | Copies of the hive files as they looked at the end of the text-mode stage in Setup. Setup has two stages: text mode and graphics mode. The hive is copied to a .sav file after the text-mode stage of setup to protect it from errors that might occur if the graphics-mode stage of setup fails. If setup fails during the graphics-mode stage, only the graphics-mode stage is repeated when the computer is restarted; the .sav file is used to restore the hive data

The following table lists the standard hives and their supporting files under Windows NT/Windows 2000.

Registry hive | Supporting files
HKEY_LOCAL_MACHINE\SAM | Sam, Sam.log, Sam.sav
HKEY_LOCAL_MACHINE\Security | Security, Security.log, Security.sav
HKEY_LOCAL_MACHINE\Software | Software, Software.log, Software.sav
HKEY_LOCAL_MACHINE\System | System, System.alt, System.log, System.sav
HKEY_CURRENT_CONFIG | System, System.alt, System.log, System.sav
HKEY_CURRENT_USER | Ntuser.dat, Ntuser.dat.log
HKEY_USERS\.DEFAULT | Default, Default.log, Default.sav

Hives are created for each user to store information on that user's usage of the system. Refer to User Profile Hives for more information.


User Profile Hives

Each time a new user logs on to a computer, a new hive is created for that user with a separate file for the user profile. This is called the user profile hive. A user's hive contains specific registry information pertaining to the user's application settings, desktop, environment, network connections, and printers. User profile hives are located under the HKEY_USERS key.

Under Windows NT/Windows 2000, the supporting file for the user profile hive for a particular user is located in HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\CurrentVersion\ProfileList\SID\ProfileImagePath, and is named Ntuser.dat. The value of ProfileImagePath is a binary representation of the directory name of the user's profile, which includes the user's name. Use the Registry Editor to display this binary value as a string.


The HKEY_CLASSES_ROOT Key

The HKEY_CLASSES_ROOT (HKCR) key contains file extension associations and COM class registration information such as ProgIDs, CLSIDs, and IIDs.

Starting with Windows 2000, class registration and file extension information is stored under both the HKEY_LOCAL_MACHINE key and the HKEY_CURRENT_USER key. The HKEY_LOCAL_MACHINE\Software\Classes key contains default settings that can apply to all users on the local computer. The HKEY_CURRENT_USER\Software\Classes key contains settings that apply only to the interactive user. The HKEY_CLASSES_ROOT key provides a view of the registry that merges the information from these two sources. HKEY_CLASSES_ROOT also provides this merged view for older applications that are running on Windows 2000.

The user-specific settings have priority over the default settings. For example, the default setting might specify Microsoft® WordPad as the application that handles .doc files. But each user can override this setting by specifying Microsoft Word or some other word processor in his or her registry hive. The user-specific information is stored in the user's registry hive, which is loaded under HKEY_CURRENT_USER when the user logs on.

There are a number of registry functions, such as RegOpenKeyEx or RegQueryValueEx, for which you can specify the HKEY_CLASSES_ROOT key. When you call these functions from a process running in the security context of the interactive user, the system merges the default settings in HKEY_LOCAL_MACHINE\Software\Classes with the interactive user's settings at HKEY_CURRENT_USER\Software\Classes. For more information on how these settings are merged, see Merged View of HKEY_CLASSES_ROOT.

To change the settings for the interactive user, write the changes under HKEY_CURRENT_USER\Software\Classes rather than using the HKEY_CLASSES_ROOT key. To change the default settings, write to HKEY_LOCAL_MACHINE\Software\Classes. If you write keys or values to the HKEY_CLASSES_ROOT key, the system by default stores the information under HKEY_LOCAL_MACHINE\Software\Classes. However, if the key to be written to already exists under HKEY_CURRENT_USER\Software\Classes, the information is stored under HKEY_CURRENT_USER. Suppose, for example, you try to create a key named B under the HKEY_CLASSES_ROOT\CLSID\A key. If the HKEY_CURRENT_USER\Software\Classes\CLSID\A key already exists, the new key is created under HKEY_CURRENT_USER, and HKEY_LOCAL_MACHINE is unchanged. However, if HKEY_CURRENT_USER\Software\Classes\CLSID\A key does not exist, the new key is created under HKEY_LOCAL_MACHINE, and HKEY_CURRENT_USER is unchanged.

Processes running in a security context other than that of the interactive user should not use the HKEY_CLASSES_ROOT key with registry functions such as RegOpenKeyEx or RegQueryValueEx. Instead, such processes can explicitly open the HKEY_LOCAL_MACHINE\Software\Classes key to access the default settings. To open a registry key that merges the contents of HKEY_LOCAL_MACHINE\Software\Classes with the settings for a specified user, these processes can call the RegOpenUserClassesRoot function. For example, a thread that is impersonating a client can call RegOpenUserClassesRoot if it needs to retrieve a merged view for the client being impersonated. Note that RegOpenUserClassesRoot fails if the user profile for the specified user has not been loaded. The system automatically loads the profile for the interactive user when logging on. For other users, you need to call the LoadUserProfile function to explicitly load the user's profile.

For Windows NT 4.0 and earlier, and Windows 95/ 98, HKEY_CLASSES_ROOT is an alias for the HKEY_LOCAL_MACHINE\Software\Classes key. All users share the information in HKEY_LOCAL_MACHINE. For computers with multiple users, this means that all users have the same file extension associations and COM class registrations.


Merged View of HKEY_CLASSES_ROOT

Starting with Windows 2000, class registration and file extension information is stored under both the HKEY_LOCAL_MACHINE key and the HKEY_CURRENT_USER key. The HKEY_LOCAL_MACHINE\Software\Classes key contains default settings that can apply to all users on the local computer. The HKEY_CURRENT_USER\Software\Classes key contains settings that apply only to the interactive user. The HKEY_CLASSES_ROOT key provides a view of the registry that merges the information from these two sources.

The RegOpenUserClassesRoot function provides a similar merged view for processes, such as Win32 services, that are dealing with clients other than the interactive user. In this case, the view merges the HKEY_LOCAL_MACHINE\Software\Classes information with the information from the Software\Classes key of the user's registry hive.

The system uses the following rules to merge information from the two sources:

  • The merged view includes all subkeys of the HKEY_CURRENT_USER\Software\Classes key.
  • The merged view includes all immediate subkeys of the HKEY_LOCAL_MACHINE\Software\Classes key that do not duplicate the subkeys of HKEY_CURRENT_USER\Software\Classes.
  • At the end of this topic is a list of subkeys that are found in both HKEY_LOCAL_MACHINE\Software\Classes and HKEY_CURRENT_USER\Software\Classes. The immediate subkeys of these keys from the HKEY_LOCAL_MACHINE tree are included in the merged view only if they are not duplicates of immediate subkeys from the HKEY_CURRENT_USER tree. The merged view does not include the HKEY_LOCAL_MACHINE contents of duplicate subkeys.

The following example shows a set of subkeys under the HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER keys and the resulting merged view of HKEY_CLASSES_ROOT.

HKEY_LOCAL_MACHINE\Software\Classes

\CLSID

\2

\4

\localserver32

\inprocserver32

\7

HKEY_CURRENT_USER\Software\Classes

\CLSID

\1

\4

\localserver

\6

\10

\localserver

HKEY_CLASSES_ROOT

\CLSID

\1

\2

\4

\localserver

\6

\7

\10

\localserver

The following subkeys are found in both HKEY_LOCAL_MACHINE\Software\Classes and HKEY_CURRENT_USER\Software\Classes. From the HKEY_LOCAL_MACHINE tree, the immediate subkeys of these keys are included in the merged view only if they are not duplicates of immediate subkeys from the HKEY_CURRENT_USER tree. The merged view does not include the HKEY_LOCAL_MACHINE contents of duplicate subkeys.

    \*
    \*\shellex
    \*\shellex\ContextMenuHandlers
    \*\shellex\PropertyShellHandlers
    \AppID
    \ClsID
    \Component Categories
    \Drive
    \Drive\shellex
    \Drive\shellex\ContextMenuHandlers
    \Drive\shellex\PropertyShellHandlers
    \FileType
    \Folder
    \Folder\shellex
    \Folder\shellex\ColumnHandler
    \Folder\shellex\ContextMenuHandlers
    \Folder\shellex\ExtShellFolderViews
    \Folder\shellex\PropertySheetHandlers
    \Installer\Components
    \Installer\Features
    \Installer\Products
    \Interface
    \Mime
    \Mime\Database
    \Mime\Database\Charset
    \Mime\Database\Codepage
    \Mime\Database\Content Type
    \Typelib)


Categories of Data

Before putting data into the registry, an application should divide the data into two categories: computer-specific data and user-specific data. By making this distinction, an application can support multiple users, and yet locate user-specific data over a network and use that data in different locations, allowing location-independent user profile data. (A user profile is a set of configuration data saved for every user.)

When the application is installed, it should record the computer-specific data under the HKEY_LOCAL_MACHINE key. In particular, it should create keys for the company name, product name, and version number, as shown in the following example:

HKEY_LOCAL_MACHINE\Software\MyCompany\MyProduct\1.0

If the application supports COM, it should record that data under HKEY_LOCAL_MACHINE\Software\Classes.

An application should record user-specific data under the HKEY_CURRENT_USER key, as shown in the following example:

HKEY_CURRENT_USER\Software\MyCompany\MyProduct\1.0\...


Opening, Creating, and Closing Keys

Before an application can add data to the registry, it must create or open a key. To create or open a key, an application always refers to the key as a subkey of a currently open key. The following predefined keys are always open: HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, HKEY_USERS, and HKEY_CURRENT_USER. An application uses the RegOpenKeyEx function to open a key and the RegCreateKeyEx function to create a key.

Note RegOpenKey and RegCreateKey functions are provided only for compatibility with Windows version 3.1. Applications should use the RegOpenKeyEx and RegCreateKeyEx functions.

An application can use the RegCloseKey function to close a key and write the data it contains into the registry. RegCloseKey does not necessarily write the data to the registry before returning; it can take as much as several seconds for the cache to be flushed to the hard disk. If an application must explicitly write registry data to the hard disk, it can use the RegFlushKey function. RegFlushKey, however, uses many system resources and should be called only when absolutely necessary.


Writing and Deleting Registry Data

An application can use either the RegSetValue or RegSetValueEx function to associate a value and its data with a key. RegSetValue works only with strings (values having the REG_SZ type). RegSetValueEx, however, can write values with any type of data. Either of these functions can create a key and its value at the same time. For a list of the value types supported by RegSetValueEx, see Registry Value Types.

To delete a value from a key, an application can use the RegDeleteValue function. To delete a key, it can use the RegDeleteKey function. A deleted key is not removed until the last handle to it has been closed. Subkeys and values cannot be created under a deleted key.

Security attributes can also be assigned to registry keys. For more information on this, refer to Security Attributes for Registry Keys.


Security Attributes for Registry Keys

You may want to restrict access to specific data in the registry—for example, to sensitive performance data that, by default, is accessible to anyone, including remote users. There are also times when an application must access certain registry keys that its user does not have access to. For these reasons, Windows NT/Windows 2000 assigns a level of security to each registry key.

Note Taking ownership of a registry key is not a common operation. It is typically performed by an administrator as a last resort to gain access to a registry key.

To change this security level for a key under Windows NT/Windows 2000, do the following.

  1. Open the key by calling the RegOpenKeyEx function. If the user does not have the correct access to the registry key, the open operation will fail. The solution to this problem is to first enable the TakeOwnership privilege and then open the registry key with WRITE_OWNER access by calling the RegOpenKeyEx function in the following way. In this example, the name of the target key is "Testkey".
    RegOpenKeyEx (HKEY_CLASSES_ROOT, "Testkey", 0, WRITE_OWNER, &hKey);

    This function call will return a handle to the registry.

  2. Pass the handle returned by RegOpenKeyEx into the following call to RegSetKeySecurity to take ownership of the key.
    RegSetKeySecurity (hKey, OWNER_SECURITY_INFORMATION, &SecurityDescriptor);

Keep in mind that you need to initialize the SECURITY_DESCRIPTOR structure passed to RegSetKeySecurity as the SecurityDescriptor parameter, and set its owner field to your own owner SID. To obtain your owner SID, call LookupAccountName .


Retrieving Data from the Registry

To retrieve data from the registry, an application typically enumerates the subkeys of a key until it finds a particular one and then retrieves data from the value or values associated with it. An application can call either the RegEnumKey or RegEnumKeyEx function to enumerate the subkeys of a given key. RegEnumKeyEx returns a subkey and its class, but RegEnumKey returns only the subkey, not the class.

To retrieve detailed data about a particular subkey, an application can call the RegQueryInfoKey function. The RegGetKeySecurity function retrieves a copy of the security descriptor protecting a key.

An application can use the RegEnumValue function to enumerate the values for a given key, and the RegQueryValue or RegQueryValueEx function to retrieve a particular value for a key. An application typically calls RegEnumValue to determine the value names and then RegQueryValueEx to retrieve the data for the names.

RegQueryValue and RegQueryValueEx differ in how they treat unexpanded references to environment variables. If an unnamed value contains an unexpanded environment variable (for example, %PATH%), RegQueryValue expands the variable into the storage buffer provided as one of its parameters. RegQueryValueEx, however, does not expand these references. (Applications can also use the ExpandEnvironmentStrings function to expand environment variables.)

The RegQueryMultipleValues function retrieves the type and data for a list of value names associated with an open registry key. This function is useful for dynamic key providers because it assures consistency of data by retrieving multiple values in an atomic operation. This is more efficient than calling RegQueryValue multiple times, particularly across a network, because it can retrieve the values with one network transaction.

The RegNotifyChangeKeyValue function notifies the calling thread through an event when changes to the attributes or contents of a specified registry key are made. The function does not notify the caller if the key is deleted. If the thread that calls RegNotifyChangeKeyValue exits, the notification event is signaled and the monitoring of the registry key is stopped.

You can control or specify what changes should be reported through the use of a notify filter or flag. Usually, changes are reported by signaling an event that you specify to the function. Note that the RegNotifyChangeKeyValue function does not work with remote handles.

The following example code uses the registry interface functions described in this section to determine which variant of Windows NT/Windows 2000—Server or Workstation—is running by querying the ProductType subkey of the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ProductOptions key.

#define RTN_UNKNOWN 0
#define RTN_SERVER 1
#define RTN_WORKSTATION 2
#define RTN_NTAS 3
#define RTN_ERROR 13

DWORD GetWindowsVariant(void)
{
    #define MY_BUFSIZE 32    // Arbitrary initial value.
                             // Dynamic allocation will be used.
    HKEY hKey;
    TCHAR szProductType[MY_BUFSIZE];
    DWORD dwBufLen = MY_BUFSIZE;
    LONG lRet;

    if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
        TEXT("SYSTEM\\CurrentControlSet\\Control\\ProductOptions"),
                    0,
                    KEY_QUERY_VALUE,
                    &hKey) != ERROR_SUCCESS) return RTN_ERROR;

    lRet = RegQueryValueEx(hKey,
                    TEXT("ProductType"),
                    NULL,
                    NULL,
                    (LPBYTE)szProductType,
                    &dwBufLen);

    RegCloseKey(hKey);

    if(lRet != ERROR_SUCCESS) return RTN_ERROR;

    // check product options, in order of likelihood
    if(lstrcmpi(TEXT("WINNT"), szProductType) == 0)
         return RTN_WORKSTATION;
    if(lstrcmpi(TEXT("SERVERNT"), szProductType) == 0)
         return RTN_SERVER;
    if(lstrcmpi(TEXT("LANMANNT"), szProductType) == 0)
         return RTN_NTAS;
    // else return "unknown variant" code
    else return RTN_UNKNOWN;
}


Registry Files

Applications can save part of the registry in a file and then load the contents of the file back into the registry. A registry file is useful when a large amount of data is being manipulated, when many entries are being made in the registry, or when the data is transitory and must be loaded and then unloaded again. Applications that back up and restore parts of the registry are likely to use registry files.

To save a key and its subkeys and values to a registry file, an application can call the RegSaveKey function.

RegSaveKey creates the file with the following information depending upon which operating system it is running on.

Windows operating system version | File attributes | Location of saved registry if no path is specified | Error returned if a file already exists
Windows 95 | Archive, hidden, read-only system | Created in the Windows directory for both local and remote keys | Error code 1016, ERROR_REGISTRY_IO_FAILED
Windows NT | Archive | Created in the current directory of the process for a local key, and in the %systemroot%\system directory for a remote key. | Error code 183, ERROR_ALREADY_EXISTS

To write the registry file back to the registry, an application can use the RegLoadKey, RegReplaceKey, or RegRestoreKey function.

RegLoadKey loads registry data from a specified file into a specified subkey under HKEY_USERS or HKEY_LOCAL_MACHINE on the calling application's computer or on a remote computer. The function creates the specified subkey if it does not already exist. After calling this function, an application can use the RegUnLoadKey function to restore the registry to its previous state.

RegReplaceKey replaces a key and all its subkeys and values in the registry with the data contained in a specified file. The new data takes effect the next time the system is started.

RegRestoreKey loads registry data from a specified file into a specified key on the calling application's computer or on a remote computer. This function replaces the subkeys and values below the specified key with the subkeys and values that follow the top-level key in the file.

The RegConnectRegistry function establishes a connection to a predefined registry handle on another computer. An application uses this function primarily to access information from a remote registry on other machines in a network environment, which you can also do by using the Registry Editor. You might want to access a remote registry to back up a registry or regulate network access to it. Note that you must have appropriate permissions to access a remote registry using this function.

To use RegConnectRegistry on Windows 95, you need to install the remote registry service. Refer to the function specification of RegConnectRegistry for more information on how to do this.


Registry Key Security and Access Rights

Windows NT/Windows 2000 security enables you to control access to registry keys. For more information about security, see Access-Control Model.

You can specify a security descriptor for a registry key when you call the RegCreateKeyEx function. To get or set the security descriptor of a registry key, call the GetNamedSecurityInfo, SetNamedSecurityInfo, GetSecurityInfo, or SetSecurityInfo function.

When you call the RegOpenKeyEx function, the system checks the requested access rights against the key's security descriptor.

The valid access rights for registry keys include the DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER standard access rights. Registry keys do not support the SYNCHRONIZE standard access right. The following table lists the specific access rights for registry key objects.

Value | Meaning
KEY_ALL_ACCESS | Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK values.
KEY_CREATE_LINK | Required to create a link to a registry-key.
KEY_CREATE_SUB_KEY | Required to create a subkey of a registry-key.
KEY_ENUMERATE_SUB_KEYS | Required to enumerate the subkeys of a registry-key.
KEY_EXECUTE | Equivalent to KEY_READ.
KEY_NOTIFY | Required to request change notifications for a registry key or for subkeys of a registry key.
KEY_QUERY_VALUE | Required to query a value of a registry-key.
KEY_READ | Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.
KEY_SET_VALUE | Required to create or set a value of a registry-key.
KEY_WRITE | Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY values.

You can request the ACCESS_SYSTEM_SECURITY access right to a registry key if you want to read or write the key's SACL. For more information, see Access-Control Lists (ACLs) and SACL Access Right.


Using the Registry

The following example demonstrates the use of the RegQueryInfoKey, RegEnumKey, and RegEnumValue functions. The hKey parameter passed to each function is a handle to an open key. This key must be opened before the function call and closed afterward.

// QueryKey - enumerates the subkeys of a given key and the associated
//    values and then copies the information about the keys and values
//    into a pair of edit controls and list boxes.
// hDlg - dialog box that contains the edit controls and list boxes
// hKey - key whose subkeys and values are to be enumerated

VOID QueryKey(HWND hDlg, HANDLE hKey)
{
    CHAR     achKey[MAX_PATH];
    CHAR     achClass[MAX_PATH] = "";  // buffer for class name
    DWORD    cchClassName = MAX_PATH;  // length of class string
    DWORD    cSubKeys;                 // number of subkeys
    DWORD    cbMaxSubKey;              // longest subkey size
    DWORD    cchMaxClass;              // longest class string
    DWORD    cValues;              // number of values for key
    DWORD    cchMaxValue;          // longest value name
    DWORD    cbMaxValueData;       // longest value data
    DWORD    cbSecurityDescriptor; // size of security descriptor
    FILETIME ftLastWriteTime;      // last write time

    DWORD i, j;
    DWORD retCode, retValue;

    CHAR  achValue[MAX_VALUE_NAME];
    DWORD cchValue = MAX_VALUE_NAME;
    CHAR  achBuff[80];

    // Get the class name and the value count.
    RegQueryInfoKey(hKey,        // key handle
        achClass,                // buffer for class name
        &cchClassName,           // length of class string
        NULL,                    // reserved
        &cSubKeys,               // number of subkeys
        &cbMaxSubKey,            // longest subkey size
        &cchMaxClass,            // longest class string
        &cValues,                // number of values for this key
        &cchMaxValue,            // longest value name
        &cbMaxValueData,         // longest value data
        &cbSecurityDescriptor,   // security descriptor
        &ftLastWriteTime);       // last write time

    SetDlgItemText(hDlg, IDE_CLASS, achClass);
    SetDlgItemInt(hDlg, IDE_CVALUES, cValues, FALSE);

    SendMessage(GetDlgItem(hDlg, IDL_LISTBOX),
        LB_ADDSTRING, 0, (LONG) "..");

    // Enumerate the child keys, looping until RegEnumKey fails. Then
    // get the name of each child key and copy it into the list box.

    SetCursor(LoadCursor(NULL, IDC_WAIT));
    for (i = 0, retCode = ERROR_SUCCESS;
            retCode == ERROR_SUCCESS; i++)
    {
        retCode = RegEnumKey(hKey, i, achKey, MAX_PATH);
        if (retCode == (DWORD)ERROR_SUCCESS)
        {
            SendMessage(GetDlgItem(hDlg, IDL_LISTBOX),
                LB_ADDSTRING, 0, (LONG) achKey);
        }
    }
    SetCursor(LoadCursor (NULL, IDC_ARROW));

    // Enumerate the key values.
    SetCursor(LoadCursor(NULL, IDC_WAIT));

    if (cValues)
    {
        for (j = 0, retValue = ERROR_SUCCESS;
                j < cValues; j++)
        {
            cchValue = MAX_VALUE_NAME;
            achValue[0] = '\0';
            retValue = RegEnumValue(hKey, j, achValue,
                &cchValue,
                NULL,
                NULL,    // &dwType,
                NULL,    // &bData,
                NULL);   // &bcData

            if (retValue != (DWORD) ERROR_SUCCESS &&
                    retValue != ERROR_INSUFFICIENT_BUFFER)
            {
                wsprintf (achBuff,
                    "Line:%d 0 based index = %d, retValue = %d, "
                     "ValueLen = %d",
                     __LINE__, j, retValue, cchValue);
                MessageBox (hDlg, achBuff, "Debug", MB_OK);
            }

            achBuff[0] = '\0';

            // Add each value to a list box.
            if (!lstrlen(achValue))
                lstrcpy(achValue, "<NO NAME>");
            wsprintf(achBuff, "%d) %s ", j, achValue);
            SendMessage(GetDlgItem(hDlg,IDL_LISTBOX2),
                LB_ADDSTRING, 0, (LONG) achBuff);
        }

    SetCursor(LoadCursor(NULL, IDC_ARROW));
}


Registry Reference

The following elements are used with the registry.

  • Registry Functions
  • Registry Structures


Registry Functions

The following functions are used with the registry.

Function | Description
RegCloseKey | Releases a handle to the specified registry key.
RegConnectRegistry | Establishes a connection to a predefined registry handle on another computer.
RegCreateKeyEx | Creates the specified registry key.
RegDeleteKey | Deletes a subkey.
RegDeleteValue | Removes a named value from the specified registry key.
RegDisablePredefinedCache | Disables the predefined registry handle table of HKEY_CURRENT_USER for the specified process.
RegEnumKeyEx | Enumerates subkeys of the specified open registry key.
RegEnumValue | Enumerates the values for the specified open registry key.
RegFlushKey | Writes all the attributes of the specified open registry key into the registry.
RegGetKeySecurity | Retrieves a copy of the security descriptor protecting the specified open registry key.
RegLoadKey | Creates a subkey under HKEY_USERS or HKEY_LOCAL_MACHINE and stores registration information from a specified file into that subkey.
RegNotifyChangeKeyValue | Notifies the caller about changes to the attributes or contents of a specified registry key.
RegOpenCurrentUser | Retrieves a handle to the HKEY_CURRENT_USER key for the user the current thread is impersonating.
RegOpenKeyEx | Opens the specified registry key.
RegOpenUserClassesRoot | Retrieves a handle to the HKEY_CLASSES_ROOT key for the specified user.
RegOverridePredefKey | Maps a predefined registry key to a specified registry key.
RegQueryInfoKey | Retrieves information about the specified registry key.
RegQueryMultipleValues | Retrieves the type and data for a list of value names associated with an open registry key.
RegQueryValueEx | Retrieves the type and data for a specified value name associated with an open registry key.
RegReplaceKey | Replaces the file backing a registry key and all its subkeys with another file.
RegRestoreKey | Reads the registry information in a specified file and copies it over the specified key.
RegSaveKey | Saves the specified key and all of its subkeys and values to a new file.
RegSetKeySecurity | Sets the security of an open registry key.
RegSetValueEx | Sets the data and type of a specified value under a registry key.
RegUnLoadKey | Unloads the specified registry key and its subkeys from the registry.

The following are the initialization-file functions. They retrieve information from and copy information to a system- or application-defined initialization file. These functions are provided only for compatibility with 16-bit versions of Windows. New applications should use the registry.

Function | Description
GetPrivateProfileInt | Retrieves an integer associated with a key in the specified section of an initialization file.
GetPrivateProfileSection | Retrieves all the keys and values for the specified section of an initialization file.
GetPrivateProfileSectionNames | Retrieves the names of all sections in an initialization file.
GetPrivateProfileString | Retrieves a string from the specified section in an initialization file.
GetPrivateProfileStruct | Retrieves the data associated with a key in the specified section of an initialization file.
GetProfileInt | Retrieves an integer from a key in the specified section of the Win.ini file.
GetProfileSection | Retrieves all the keys and values for the specified section of the Win.ini file.
GetProfileString | Retrieves the string associated with a key in the specified section of the Win.ini file.
WritePrivateProfileSection | Replaces the keys and values for the specified section in an initialization file.
WritePrivateProfileString | Copies a string into the specified section of an initialization file.
WritePrivateProfileStruct | Copies data into a key in the specified section of an initialization file.
WriteProfileSection | Replaces the contents of the specified section in the Win.ini file with specified keys and values.
WriteProfileString | Copies a string into the specified section of the Win.ini file.

Obsolete Functions

These functions are provided only for compatibility with 16-bit versions of Windows.

RegCreateKey
RegEnumKey
RegOpenKey
RegQueryValue
RegSetValue


GetPrivateProfileInt

The GetPrivateProfileInt function retrieves an integer associated with a key in the specified section of an initialization file.

Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.

UINT GetPrivateProfileInt(
  LPCTSTR lpAppName,  // section name
  LPCTSTR lpKeyName,  // key name
  INT nDefault,       // return value if key name not found
  LPCTSTR lpFileName  // initialization file name
);

Parameters

lpAppName
[in] Pointer to a null-terminated string specifying the name of the section in the initialization file.
lpKeyName
[in] Pointer to the null-terminated string specifying the name of the key whose value is to be retrieved. This value is in the form of a string; the GetPrivateProfileInt function converts the string into an integer and returns the integer.
nDefault
[in] Specifies the default value to return if the key name cannot be found in the initialization file.
lpFileName
[in] Pointer to a null-terminated string that specifies the name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.

Return Values

The return value is the integer equivalent of the string following the specified key name in the specified initialization file. If the key is not found, the return value is the specified default value. If the value of the key is less than zero, the return value is zero.

Remarks

The function searches the file for a key that matches the name specified by the lpKeyName parameter under the section name specified by the lpAppName parameter. A section in the initialization file must have the following form:

[section]
key=value
      .
      .
      .

The GetPrivateProfileInt function is not case-sensitive; the strings in lpAppName and lpKeyName can be a combination of uppercase and lowercase letters.

An application can use the GetProfileInt function to retrieve an integer value from the Win.ini file.

Windows NT/2000 or later: Calls to private profile functions may be mapped to the registry instead of to the specified initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

This mapping is likely if an application modifies system-component initialization files, such as Control.ini, System.ini, and Winfile.ini. In these cases, the GetPrivateProfileInt function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetProfileInt, WritePrivateProfileString


GetPrivateProfileSection

The GetPrivateProfileSection function retrieves all the keys and values for the specified section of an initialization file.

Windows 95/98/Me: The specified profile section must not exceed 32K.

Windows NT/2000 or later: The specified profile section has no size limit.

Note This function is provided only for compatibility with 16-bit applications written for Windows. Applications should store initialization information in the registry.

DWORD GetPrivateProfileSection(
  LPCTSTR lpAppName,        // section name
  LPTSTR lpReturnedString,  // return buffer
  DWORD nSize,              // size of return buffer
  LPCTSTR lpFileName        // initialization file name
);

Parameters

lpAppName
[in] Pointer to a null-terminated string specifying the name of the section in the initialization file.
lpReturnedString
[out] Pointer to a buffer that receives the key name and value pairs associated with the named section. The buffer is filled with one or more null-terminated strings; the last string is followed by a second null character.
nSize
[in] Specifies the size, in TCHARs, of the buffer pointed to by the lpReturnedString parameter.

Windows 95/98/Me: The maximum buffer size is 32,767 characters.

lpFileName
[in] Pointer to a null-terminated string that specifies the name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.

Return Values

The return value specifies the number of characters copied to the buffer, not including the terminating null character. If the buffer is not large enough to contain all the key name and value pairs associated with the named section, the return value is equal to nSize minus two.

Remarks

The data in the buffer pointed to by the lpReturnedString parameter consists of one or more null-terminated strings, followed by a final null character. Each string has the following format:

key=string

The GetPrivateProfileSection function is not case-sensitive; the string pointed to by the lpAppName parameter can be a combination of uppercase and lowercase letters.

This operation is atomic; no updates to the specified initialization file are allowed while the key name and value pairs for the section are being copied to the buffer pointed to by the lpReturnedString parameter.

Windows NT/2000 or later: Calls to private profile functions may be mapped to the registry instead of to the specified initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

This mapping is likely if an application modifies system-component initialization files, such as Control.ini, System.ini, and Winfile.ini. In these cases, the GetPrivateProfileSection function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Windows NT/2000 or later: Comments (any line that starts with a semicolon) are stripped out and not returned in the lpReturnedString buffer.

Windows 95/98/Me: The lpReturnedString buffer receives a copy of the entire section, including comments.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetProfileSection, WritePrivateProfileSection


GetPrivateProfileSectionNames

The GetPrivateProfileSectionNames function retrieves the names of all sections in an initialization file.

Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.

DWORD GetPrivateProfileSectionNames(
  LPTSTR lpszReturnBuffer,  // return buffer
  DWORD nSize,              // size of return buffer
  LPCTSTR lpFileName        // initialization file name
);

Parameters

lpszReturnBuffer
[out] Pointer to a buffer that receives the section names associated with the named file. The buffer is filled with one or more null-terminated strings; the last string is followed by a second null character.
nSize
[in] Specifies the size, in TCHARs, of the buffer pointed to by the lpszReturnBuffer parameter.
lpFileName
[in] Pointer to a null-terminated string that specifies the name of the initialization file. If this parameter is NULL, the function searches the Win.ini file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.

Return Values

The return value specifies the number of characters copied to the specified buffer, not including the terminating null character. If the buffer is not large enough to contain all the section names associated with the specified initialization file, the return value is equal to the length specified by nSize minus two.

Remarks

This operation is atomic; no updates to the initialization file are allowed while the section names are being copied to the buffer.

Calls to profile functions might be mapped to the registry instead of to the initialization files. When the operation has been mapped, the GetPrivateProfileSectionNames function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetPrivateProfileSection, WritePrivateProfileSection


GetPrivateProfileString

The GetPrivateProfileString function retrieves a string from the specified section in an initialization file.

Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.

DWORD GetPrivateProfileString(
  LPCTSTR lpAppName,        // section name
  LPCTSTR lpKeyName,        // key name
  LPCTSTR lpDefault,        // default string
  LPTSTR lpReturnedString,  // destination buffer
  DWORD nSize,              // size of destination buffer
  LPCTSTR lpFileName        // initialization file name
);

Parameters

lpAppName
[in] Pointer to a null-terminated string that specifies the name of the section containing the key name. If this parameter is NULL, the GetPrivateProfileString function copies all section names in the file to the supplied buffer.
lpKeyName
[in] Pointer to the null-terminated string specifying the name of the key whose associated string is to be retrieved. If this parameter is NULL, all key names in the section specified by the lpAppName parameter are copied to the buffer specified by the lpReturnedString parameter.
lpDefault
[in] Pointer to a null-terminated default string. If the lpKeyName key cannot be found in the initialization file, GetPrivateProfileString copies the default string to the lpReturnedString buffer. This parameter cannot be NULL.

Avoid specifying a default string with trailing blank characters. The function inserts a null character in the lpReturnedString buffer to strip any trailing blanks.

Windows 95/98/Me: Although lpDefault is declared as a constant parameter, the system strips any trailing blanks by inserting a null character into the lpDefault string before copying it to the lpReturnedString buffer.

Windows NT/2000 or later: The system does not modify the lpDefault string. This means that if the default string contains trailing blanks, the lpReturnedString and lpDefault strings will not match when compared using the lstrcmp function.

lpReturnedString
[out] Pointer to the buffer that receives the retrieved string.
nSize
[in] Specifies the size, in TCHARs, of the buffer pointed to by the lpReturnedString parameter.
lpFileName
[in] Pointer to a null-terminated string that specifies the name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.

Return Values

The return value is the number of characters copied to the buffer, not including the terminating null character.

If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.

If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two.

Remarks

The GetPrivateProfileString function searches the specified initialization file for a key that matches the name specified by the lpKeyName parameter under the section heading specified by the lpAppName parameter. If it finds the key, the function copies the corresponding string to the buffer. If the key does not exist, the function copies the default character string specified by the lpDefault parameter. A section in the initialization file must have the following form:

[section]
key=string
      .
      .
      .

If lpAppName is NULL, GetPrivateProfileString copies all section names in the specified file to the supplied buffer. If lpKeyName is NULL, the function copies all key names in the specified section to the supplied buffer. An application can use this method to enumerate all of the sections and keys in a file. In either case, each string is followed by a null character and the final string is followed by a second null character. If the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters.

If the string associated with lpKeyName is enclosed in single or double quotation marks, the marks are discarded when the GetPrivateProfileString function retrieves the string.

The GetPrivateProfileString function is not case-sensitive; the strings can be a combination of uppercase and lowercase letters.

To retrieve a string from the Win.ini file, use the GetProfileString function.

Windows NT/2000 or later: Calls to private profile functions may be mapped to the registry instead of to the specified initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

This mapping is likely if an application modifies system-component initialization files, such as Control.ini, System.ini, and Winfile.ini. In these cases, the GetPrivateProfileString function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetProfileString, WritePrivateProfileString


GetPrivateProfileStruct

The GetPrivateProfileStruct function retrieves the data associated with a key in the specified section of an initialization file. As it retrieves the data, the function calculates a checksum and compares it with the checksum calculated by the WritePrivateProfileStruct function when the data was added to the file.

Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.

BOOL GetPrivateProfileStruct(
  LPCTSTR lpszSection,  // section name
  LPCTSTR lpszKey,      // key name
  LPVOID lpStruct,      // return buffer
  UINT uSizeStruct,     // size of return buffer
  LPCTSTR szFile        // initialization file name
);

Parameters

lpszSection
[in] Pointer to a null-terminated string specifying the name of the section in the initialization file.
lpszKey
[in] Pointer to the null-terminated string specifying the name of the key whose data is to be retrieved.
lpStruct
[out] Pointer to the buffer that receives the data associated with the file, section, and key names.
uSizeStruct
[in] Specifies the size, in bytes, of the buffer pointed to by the lpStruct parameter.
szFile
[in] Pointer to a null-terminated string that specifies the name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero.

Remarks

A section in the initialization file must have the following form:

[section]
key=data
      .
      .
      .

Calls to private profile functions might be mapped to the registry instead of to the specified initialization files. This mapping is likely if an application modifies system-component initialization files, such as Control.ini, System.ini, and Winfile.ini. In these cases, the GetPrivateProfileStruct function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, WritePrivateProfileStruct


GetProfileInt

The GetProfileInt function retrieves an integer from a key in the specified section of the Win.ini file.

Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.

UINT GetProfileInt(
  LPCTSTR lpAppName,  // section name
  LPCTSTR lpKeyName,  // key name
  INT nDefault        // default value if key name not found
);

Parameters

lpAppName
[in] Pointer to a null-terminated string that specifies the name of the section containing the key name.
lpKeyName
[in] Pointer to the null-terminated string specifying the name of the key whose value is to be retrieved. This value is in the form of a string; the GetProfileInt function converts the string into an integer and returns the integer.
nDefault
[in] Specifies the default value to return if the key name cannot be found in the initialization file.

Return Values

The return value is the integer equivalent of the string following the key name in Win.ini. If the function cannot find the key, the return value is the default value. If the value of the key is less than zero, the return value is zero.

Remarks

If the key name consists of digits followed by characters that are not numeric, the function returns only the value of the digits. For example, the function returns 102 for the following line: KeyName=102abc.

Windows NT/2000 or later: Calls to profile functions may be mapped to the registry instead of to the initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the GetProfileInt function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetPrivateProfileInt, WriteProfileString


GetProfileSection

The GetProfileSection function retrieves all the keys and values for the specified section of the Win.ini file.

Windows 95/98/Me: The specified profile section must not exceed 32K.

Windows NT/2000 or later: The specified profile section has no size limit.

Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.

DWORD GetProfileSection(
  LPCTSTR lpAppName,        // section name
  LPTSTR lpReturnedString,  // return buffer
  DWORD nSize               // size of return buffer
);

Parameters

lpAppName
[in] Pointer to a null-terminated string specifying the name of the section in the Win.ini file.
lpReturnedString
[out] Pointer to a buffer that receives the keys and values associated with the named section. The buffer is filled with one or more null-terminated strings; the last string is followed by a second null character.
nSize
[in] Specifies the size, in TCHARs, of the buffer pointed to by the lpReturnedString parameter.

Windows 95/98/Me: The maximum buffer size is 32,767 characters.

Return Values

The return value specifies the number of characters copied to the specified buffer, not including the terminating null character. If the buffer is not large enough to contain all the keys and values associated with the named section, the return value is equal to the length specified by nSize minus two.

Remarks

The format of the returned keys and values is one or more null-terminated strings, followed by a final null character. Each string has the following form:

key=string

The GetProfileSection function is not case-sensitive; the strings can be a combination of uppercase and lowercase letters.

This operation is atomic; no updates to the Win.ini file are allowed while the keys and values for the section are being copied to the buffer.

Windows NT/2000 or later: Calls to profile functions may be mapped to the registry instead of to the initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the GetProfileSection function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetPrivateProfileSection, WriteProfileSection


GetProfileString

The GetProfileString function retrieves the string associated with a key in the specified section of the Win.ini file.

Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.

DWORD GetProfileString(
  LPCTSTR lpAppName,        // section name
  LPCTSTR lpKeyName,        // key name
  LPCTSTR lpDefault,        // default string
  LPTSTR lpReturnedString,  // destination buffer
  DWORD nSize               // size of destination buffer
);

Parameters

lpAppName
[in] Pointer to a null-terminated string that specifies the name of the section containing the key. If this parameter is NULL, the function copies all section names in the file to the supplied buffer.
lpKeyName
[in] Pointer to a null-terminated string specifying the name of the key whose associated string is to be retrieved. If this parameter is NULL, the function copies all keys in the given section to the supplied buffer. Each string is followed by a null character, and the final string is followed by a second null character.
lpDefault
[in] Pointer to a null-terminated default string. If the lpKeyName key cannot be found in the initialization file, GetProfileString copies the default string to the lpReturnedString buffer. This parameter cannot be NULL.

Avoid specifying a default string with trailing blank characters. The function inserts a null character in the lpReturnedString buffer to strip any trailing blanks.

Windows 95/98/Me: Although lpDefault is declared as a constant parameter, the system strips any trailing blanks by inserting a null character into the lpDefault string before copying it to the lpReturnedString buffer.

Windows NT/2000 or later: The system does not modify the lpDefault string. This means that if the default string contains trailing blanks, the lpReturnedString and lpDefault strings will not match when compared using the lstrcmp function.

lpReturnedString
[out] Pointer to a buffer that receives the character string.
nSize
[in] Specifies the size, in TCHARs, of the buffer pointed to by the lpReturnedString parameter.

Return Values

The return value is the number of characters copied to the buffer, not including the null-terminating character.

If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.

If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two.

Remarks

If the string associated with the lpKeyName parameter is enclosed in single or double quotation marks, the marks are discarded when the GetProfileString function returns the string.

The GetProfileString function is not case-sensitive; the strings can contain a combination of uppercase and lowercase letters.

A section in the Win.ini file must have the following form:

[section]
key=string
      .
      .
      .

An application can use the GetPrivateProfileString function to retrieve a string from a specified initialization file.

The lpDefault parameter must point to a valid string, even if the string is empty (that is, even if its first character is a null character).

Windows NT/2000 or later: Calls to profile functions may be mapped to the registry instead of to the initialization files. This mapping occurs when the initialization file and section are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the GetProfileString function retrieves information from the registry, not from the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetPrivateProfileString, WriteProfileString


RegCloseKey

The RegCloseKey function releases a handle to the specified registry key.

LONG RegCloseKey(
  HKEY hKey   // handle to key to close
);

Parameters

hKey
[in] Handle to the open key to close.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The handle for a specified key should not be used after it has been closed, because it will no longer be valid. Key handles should not be left open any longer than necessary.

The RegCloseKey function does not necessarily write information to the registry before returning; it can take as much as several seconds for the cache to be flushed to the hard disk. If an application must explicitly write registry information to the hard disk, it can use the RegFlushKey function. RegFlushKey, however, uses many system resources and should be called only when necessary.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

For example, see Retrieving Data from the Registry.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Registry Overview, Registry Functions, RegCreateKey, RegCreateKeyEx, RegDeleteKey, RegFlushKey, RegOpenKey, RegOpenKeyEx, RegSetValue, RegSetValueEx


RegConnectRegistry

The RegConnectRegistry function establishes a connection to a predefined registry handle on another computer.

LONG RegConnectRegistry(
  LPCTSTR lpMachineName, // computer name
  HKEY hKey,             // predefined registry handle
  PHKEY phkResult        // buffer for remote key handle
);

Parameters

lpMachineName
[in] Pointer to a null-terminated string specifying the name of the remote computer. The string has the following form:

\\computername

If lpMachineName is NULL, the local computer name is used.

hKey
[in] Specifies the one of the following predefined registry handles on the remote computer.

HKEY_LOCAL_MACHINE
HKEY_USERS

Windows NT/2000 or later: HKEY_PERFORMANCE_DATA, if the remote computer is running Windows NT/Windows 2000

Windows 95/98/Me: HKEY_DYN_DATA, if the remote computer is running Windows 95 or Windows 98.HKEY_CURRENT_CONFIG, if the remote computer is running Windows 95 or Windows 98.

You cannot specify the HKEY_CLASSES_ROOT or HKEY_CURRENT_USER value for this parameter.

phkResult
[out] Pointer to a variable that receives a key handle identifying the predefined handle on the remote computer.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

When a handle returned by RegConnectRegistry is no longer needed, it should be closed by calling RegCloseKey.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Windows 95/98/Me: To use RegConnectRegistry, you must install the Microsoft Remote Registry service. If you don't do this, calls to RegConnectRegistry return ERROR_DLL_INIT_FAILED. Perform the following steps to install the Microsoft Remote Registry service.

To install the Microsoft Remote Registry service

  1. In the Network option in Control Panel, click Add.
  2. In the Select Network Component Type dialog box, double-click Service.
  3. In the Select Network Service dialog box, click the Have Disk button.
  4. In the Install From Disk dialog box, type the path to the ADMIN\NETTOOLS\REMOTREG directory on the Windows 95 compact disc, and then click OK.
  5. In the Install From Disk dialog box, click OK.
  6. In the Select Network Service dialog box, click Microsoft Remote Registry, and then click OK.

If you are prompted to specify the location of additional files, specify the path to the files on a shared network directory or on the compact disc.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCloseKey


RegCreateKey

The RegCreateKey function creates the specified registry key. If the key already exists in the registry, the function opens it.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should use the RegCreateKeyEx function.

LONG RegCreateKey(
  HKEY hKey,        // handle to an open key
  LPCTSTR lpSubKey, // subkey name
  PHKEY phkResult   // buffer for key handle
);

Parameters

hKey
[in] Handle to a currently open key or one of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

The key opened or created by the RegCreateKey function is a subkey of the key identified by hKey.

lpSubKey
[in] Pointer to a null-terminated string specifying the name of a key that this function opens or creates. This key must be a subkey of the key identified by the hKey parameter.

If hKey is one of the predefined keys, lpSubKey may be NULL. In that case, the handle returned by using phkResult is the same hKey handle passed in to the function.

phkResult
[out] Pointer to a variable that receives a handle to the opened or created key. When you no longer need the returned handle, call the RegCloseKey function to close it.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

An application can use the RegCreateKey function to create several keys at once. For example, an application can create a subkey four levels deep at the same time as the three preceding subkeys by specifying a string of the following form for the lpSubKey parameter:

subkey1\subkey2\subkey3\subkey4

The key identified by the hKey parameter must have been opened with KEY_CREATE_SUB_KEY access (KEY_WRITE access includes KEY_CREATE_SUB_KEY access).

If the lpSubKey parameter is the address of an empty string, the function opens and then passes back the key identified by the hKey parameter.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

For example, see Adding a Source to the Registry.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCloseKey, RegCreateKeyEx, RegDeleteKey, RegOpenKey, RegOpenKeyEx, RegSetValue


RegCreateKeyEx

The RegCreateKeyEx function creates the specified registry key. If the key already exists, the function opens it.

LONG RegCreateKeyEx(
  HKEY hKey,                                  // handle to open key
  LPCTSTR lpSubKey,                           // subkey name
  DWORD Reserved,                             // reserved
  LPTSTR lpClass,                             // class string
  DWORD dwOptions,                            // special options
  REGSAM samDesired,                          // desired security access
  LPSECURITY_ATTRIBUTES lpSecurityAttributes, // inheritance
  PHKEY phkResult,                            // key handle
  LPDWORD lpdwDisposition                     // disposition value buffer
);

Parameters

hKey
[in] Handle to a currently open key or one of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

The key opened or created by the RegCreateKeyEx function is a subkey of the key identified by the hKey parameter.

lpSubKey
[in] Pointer to a null-terminated string specifying the name of a subkey that this function opens or creates. The subkey specified must be a subkey of the key identified by the hKey parameter. This parameter cannot be NULL.

Windows NT/2000 or later: The subkey name specified by lpSubKey must not begin with the backslash character ('\'). If it does, ERROR_BAD_PATHNAME is returned.

Windows 95/98/Me: Beginning backslash characters in the subkey name specified by lpSubKey are ignored.

Reserved
Reserved; must be zero.
lpClass
[in] Pointer to a null-terminated string that specifies the class (object type) of this key. This parameter is ignored if the key already exists. No classes are currently defined; applications should pass a null string. Windows 95 and Windows 98 use this parameter only for remote registry keys; it is ignored for local registry keys. Windows NT/Windows 2000 supports this parameter for both local and remote registry keys.
dwOptions
[in] Specifies special options for the key. This parameter can be one of the following values.
Value | Meaning
REG_OPTION_NON_VOLATILE | This key is not volatile; this is the default. The information is stored in a file and is preserved when the system is restarted. The RegSaveKey function saves keys that are not volatile.
REG_OPTION_VOLATILE Windows NT/2000 or later: All keys created by the function are volatile. The information is stored in memory and is not preserved when the corresponding registry hive is unloaded. For HKEY_LOCAL_MACHINE, this occurs when the system is shut down. For registry keys loaded by the RegLoadKey function, this occurs when the corresponding RegUnloadKey is performed. The RegSaveKey function does not save volatile keys. This flag is ignored for keys that already exist.

Windows 95/98/Me: This value is ignored. If REG_OPTION_VOLATILE is specified, the RegCreateKeyEx function creates nonvolatile keys and returns ERROR_SUCCESS.
REG_OPTION_BACKUP_RESTORE | Windows NT/2000 or later: If this flag is set, the function ignores the samDesired parameter and attempts to open the key with the access required to backup or restore the key. If the calling thread has the SE_BACKUP_NAME privilege enabled, the key is opened with ACCESS_SYSTEM_SECURITY and KEY_READ access. If the calling thread has the SE_RESTORE_NAME privilege enabled, the key is opened with ACCESS_SYSTEM_SECURITY and KEY_WRITE access. If both privileges are enabled, the key has the combined accesses for both privileges.

samDesired
[in] An access mask that specifies the desired access rights to the key. This parameter can be a combination of the following values.
Value | Meaning
KEY_CREATE_LINK | Permission to create a symbolic link.
KEY_CREATE_SUB_KEY | Permission to create subkeys.
KEY_ENUMERATE_SUB_KEYS | Permission to enumerate subkeys.
KEY_EXECUTE | Permission for read access.
KEY_NOTIFY | Permission for change notification.
KEY_QUERY_VALUE | Permission to query subkey data.
KEY_SET_VALUE | Permission to set subkey data.
KEY_ALL_ACCESS | Combines the KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, KEY_CREATE_SUB_KEY, KEY_CREATE_LINK, and KEY_SET_VALUE access rights, plus all the standard access rights except SYNCHRONIZE.
KEY_READ | Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY access rights.
KEY_WRITE | Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.

lpSecurityAttributes
[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpSecurityAttributes is NULL, the handle cannot be inherited.

Windows NT/2000 or later: The lpSecurityDescriptor member of the structure specifies a security descriptor for the new key. If lpSecurityAttributes is NULL, the key gets a default security descriptor.

phkResult
[out] Pointer to a variable that receives a handle to the opened or created key. When you no longer need the returned handle, call the RegCloseKey function to close it.
lpdwDisposition
[out] Pointer to a variable that receives one of the following disposition values.
Value | Meaning
REG_CREATED_NEW_KEY | The key did not exist and was created.
REG_OPENED_EXISTING_KEY | The key existed and was simply opened without being changed.

If lpdwDisposition is NULL, no disposition information is returned.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The key that the RegCreateKeyEx function creates has no values. An application can use the RegSetValue or RegSetValueEx function to set key values.

The key identified by the hKey parameter must have been opened with KEY_CREATE_SUB_KEY access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

An application cannot create a key that is a direct child of HKEY_USERS or HKEY_LOCAL_MACHINE. An application can create subkeys in lower levels of the HKEY_USERS or HKEY_LOCAL_MACHINE trees.

An application can use RegCreateKeyEx to temporarily lock a portion of the registry. When the locking process creates a new key, it receives the disposition value REG_CREATED_NEW_KEY, indicating that it "owns" the lock. Another process attempting to create the same key receives the disposition value REG_OPENED_EXISTING_KEY, indicating that another process already owns the lock.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

For example, see Creating a Security Descriptor for a New Object.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCloseKey, RegCreateKey, RegDeleteKey, RegOpenKey, RegOpenKeyEx, RegSaveKey, SECURITY_ATTRIBUTES


RegDeleteKey

The RegDeleteKey function deletes a subkey.

Windows 95/98/Me: The function also deletes all subkeys and values. To delete a key only if the key has no subkeys or values, use the SHDeleteEmptyKey function.

Windows NT/2000 or later: The subkey to be deleted must not have subkeys. To delete a key and all its subkeys, you need to recursively enumerate the subkeys and delete them individually. To recursively delete keys, use the SHDeleteKey function.

LONG RegDeleteKey(
  HKEY hKey,         // handle to open key
  LPCTSTR lpSubKey   // subkey name
);

Parameters

hKey
[in] Handle to a currently open key or one of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

The key specified by the lpSubKey parameter must be a subkey of the key identified by hKey.

lpSubKey
[in] Pointer to a null-terminated string specifying the name of the key to delete. This parameter cannot be NULL.

Windows NT/2000 or later: The specified key must not have subkeys.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

If the function succeeds, RegDeleteKey removes the specified key from the registry. The entire key, including all of its values, is removed.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCloseKey, RegCreateKeyEx, RegOpenKeyEx, SHDeleteEmptyKey, SHDeleteKey


RegDeleteValue

The RegDeleteValue function removes a named value from the specified registry key.

LONG RegDeleteValue(
  HKEY hKey,            // handle to key
  LPCTSTR lpValueName   // value name
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

lpValueName
[in] Pointer to a null-terminated string that names the value to remove. If this parameter is NULL or points to an empty string, the value set by the RegSetValue function is removed.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The key identified by the hKey parameter must have been opened with KEY_SET_VALUE access (KEY_WRITE access includes KEY_SET_VALUE access).

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegSetValue, RegSetValueEx


RegDisablePredefinedCache

The RegDisablePredefinedCache function disables the predefined registry handle table of HKEY_CURRENT_USER for the specified process. This is a client-only function.

LONG RegDisablePredefinedCache( );

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

Any access of HKEY_CURRENT_USER after this function is called will result in open and close operations being performed on HKEY_USERS\SID_of_current_process.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Registry Overview, Registry Functions, , FormatMessage


RegEnumKey

The RegEnumKey function enumerates subkeys of the specified open registry key. The function retrieves the name of one subkey each time it is called.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should use the RegEnumKeyEx function.

LONG RegEnumKey(
  HKEY hKey,     // handle to key to query
  DWORD dwIndex, // index of subkey to query
  LPTSTR lpName, // buffer for subkey name
  DWORD cchName   // size of subkey name buffer
);

Parameters

hKey
[in] Handle to a currently open key or one of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

The keys returned are relative to the key identified by hKey.

dwIndex
[in] Specifies the index of the subkey to retrieve. This value should be zero for the first call to the RegEnumKey function and then incremented for subsequent calls.

Because subkeys are not ordered, any new subkey will have an arbitrary index. This means that the function may return subkeys in any order.

lpName
[out] Pointer to a buffer that receives the name of the subkey, including the terminating null character. This function copies only the name of the subkey, not the full key hierarchy, to the buffer.
cchName
[in] Specifies the size, in TCHARs, of the buffer pointed to by the lpName parameter. To determine the required buffer size, use the RegQueryInfoKey function to determine the size of the largest subkey for the key identified by the hKey parameter. The maximum required buffer size is (MAX_PATH + 1) characters.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Windows NT/2000 or later: If a key has been successfully retrieved and there are more keys to be retrieved, the function returns ERROR_MORE_DATA.

Remarks

To enumerate subkeys, an application should initially call the RegEnumKey function with the dwIndex parameter set to zero. The application should then increment the dwIndex parameter and call the RegEnumKey function until there are no more subkeys (until the function returns ERROR_NO_MORE_ITEMS).

The application can also set dwIndex to the index of the last key on the first call to the function and decrement the index until the subkey with index 0 is enumerated. To retrieve the index of the last subkey, use the RegQueryInfoKey.

While an application is using the RegEnumKey function, it should not make calls to any registration functions that might change the key being queried.

The key identified by the hKey parameter must have been opened with KEY_ENUMERATE_SUB_KEYS access (KEY_READ access includes KEY_ENUMERATE_SUB_KEYS access). To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

For example, see Using the Registry.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCloseKey, RegCreateKeyEx, RegDeleteKey, RegEnumKeyEx, RegOpenKeyEx, RegQueryInfoKey, RegQueryValue


RegEnumKeyEx

The RegEnumKeyEx function enumerates subkeys of the specified open registry key. The function retrieves information about one subkey each time it is called. Unlike the RegEnumKey function, RegEnumKeyEx retrieves the class name of the subkey and the time it was last modified.

LONG RegEnumKeyEx(
  HKEY hKey,                  // handle to key to enumerate
  DWORD dwIndex,              // subkey index
  LPTSTR lpName,              // subkey name
  LPDWORD lpcName,            // size of subkey buffer
  LPDWORD lpReserved,         // reserved
  LPTSTR lpClass,             // class string buffer
  LPDWORD lpcClass,           // size of class string buffer
  PFILETIME lpftLastWriteTime // last write time
);

Parameters

hKey
[in] Handle to a currently open key or one of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

The enumerated keys are subkeys of the key identified by hKey.

dwIndex
[in] Specifies the index of the subkey to retrieve. This parameter should be zero for the first call to the RegEnumKeyEx function and then incremented for subsequent calls.

Because subkeys are not ordered, any new subkey will have an arbitrary index. This means that the function may return subkeys in any order.

lpName
[out] Pointer to a buffer that receives the name of the subkey, including the terminating null character. The function copies only the name of the subkey, not the full key hierarchy, to the buffer.
lpcName
[in/out] Pointer to a variable that specifies the size, in TCHARs, of the buffer specified by the lpName parameter. This size should include the terminating null character. When the function returns, the variable pointed to by lpcName contains the number of characters stored in the buffer. The count returned does not include the terminating null character.
lpReserved
Reserved; must be NULL.
lpClass
[in/out] Pointer to a buffer that receives the null-terminated class string of the enumerated subkey. No classes are currently defined; applications should ignore this parameter. This parameter can be NULL.
lpcClass
[in/out] Pointer to a variable that specifies the size, in TCHARs, of the buffer specified by the lpClass parameter. The size should include the terminating null character. When the function returns, lpcClass contains the number of characters stored in the buffer. The count returned does not include the terminating null character. This parameter can be NULL only if lpClass is NULL.
lpftLastWriteTime
[out] Pointer to a variable that receives the time the enumerated subkey was last written to.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Windows NT/2000 or later: If a key has been successfully retrieved and there are more keys to be retrieved, the function returns ERROR_MORE_DATA.

Remarks

To enumerate subkeys, an application should initially call the RegEnumKeyEx function with the dwIndex parameter set to zero. The application should then increment the dwIndex parameter and call RegEnumKeyEx until there are no more subkeys (until the function returns ERROR_NO_MORE_ITEMS).

The application can also set dwIndex to the index of the last subkey on the first call to the function and decrement the index until the subkey with the index 0 is enumerated. To retrieve the index of the last subkey, use the RegQueryInfoKey function.

While an application is using the RegEnumKeyEx function, it should not make calls to any registration functions that might change the key being enumerated.

The key identified by hKey must have been opened with KEY_ENUMERATE_SUB_KEYS access (KEY_READ includes KEY_ENUMERATE_SUB_KEYS). Use the RegCreateKeyEx or RegOpenKeyEx function to open the key.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCreateKeyEx, RegDeleteKey, RegEnumKey, RegOpenKeyEx, RegQueryInfoKey


RegEnumValue

The RegEnumValue function enumerates the values for the specified open registry key. The function copies one indexed value name and data block for the key each time it is called.

LONG RegEnumValue(
  HKEY hKey,             // handle to key to query
  DWORD dwIndex,         // index of value to query
  LPTSTR lpValueName,    // value buffer
  LPDWORD lpcValueName,  // size of value buffer
  LPDWORD lpReserved,    // reserved
  LPDWORD lpType,        // type buffer
  LPBYTE lpData,         // data buffer
  LPDWORD lpcbData       // size of data buffer
);

Parameters

hKey
[in] Handle to a currently open key or one of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

The enumerated values are associated with the key identified by hKey.

dwIndex
[in] Specifies the index of the value to retrieve. This parameter should be zero for the first call to the RegEnumValue function and then be incremented for subsequent calls.

Because values are not ordered, any new value will have an arbitrary index. This means that the function may return values in any order.

lpValueName
[out] Pointer to a buffer that receives the name of the value, including the terminating null character.
lpcValueName
[in/out] Pointer to a variable that specifies the size, in TCHARs, of the buffer pointed to by the lpValueName parameter. This size should include the terminating null character. When the function returns, the variable pointed to by lpcValueName contains the number of characters stored in the buffer. The count returned does not include the terminating null character.
lpReserved
Reserved; must be NULL.
lpType
[out] Pointer to a variable that receives a code indicating the type of data stored in the specified value. For a list of the possible type codes, see Registry Value Types. The lpType parameter can be NULL if the type code is not required.
lpData
[out] Pointer to a buffer that receives the data for the value entry. This parameter can be NULL if the data is not required.
lpcbData
[in] Pointer to a variable that specifies the size, in bytes, of the buffer pointed to by the lpData parameter. When the function returns, the variable pointed to by the lpcbData parameter contains the number of bytes stored in the buffer. This parameter can be NULL, only if lpData is NULL.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

To enumerate values, an application should initially call the RegEnumValue function with the dwIndex parameter set to zero. The application should then increment dwIndex and call the RegEnumValue function until there are no more values (until the function returns ERROR_NO_MORE_ITEMS).

The application can also set dwIndex to the index of the last value on the first call to the function and decrement the index until the value with index 0 is enumerated. To retrieve the index of the last value, use the RegQueryInfoKey function.

While using RegEnumValue, an application should not call any registration functions that might change the key being queried.

The key identified by the hKey parameter must have been opened with KEY_QUERY_VALUE access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

To determine the maximum size of the name and data buffers, use the RegQueryInfoKey function.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

For example, see Using the Registry.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCreateKeyEx, RegEnumKey, RegEnumKeyEx, RegOpenKeyEx, RegQueryInfoKey


RegFlushKey

The RegFlushKey function writes all the attributes of the specified open registry key into the registry.

LONG RegFlushKey(
  HKEY hKey   // handle to key to write
);

Parameters

hKey
[in] Handle to a currently open key or one of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

It is not necessary to call RegFlushKey to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Lazy flushing occurs automatically and regularly after a system-specified interval of time. Registry changes are also flushed to disk at system shutdown.

Unlike RegCloseKey, the RegFlushKey function returns only when all the data has been written to the registry.

The RegFlushKey function may also write out parts of or all of the other keys. Calling this function excessively can have a negative effect on an application's performance.

An application should only call RegFlushKey if it requires absolute certainty that registry changes are on disk. In general, RegFlushKey rarely, if ever, need be used.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Registry Overview, Registry Functions, RegCloseKey, RegDeleteKey


RegLoadKey

The RegLoadKey function creates a subkey under HKEY_USERS or HKEY_LOCAL_MACHINE and stores registration information from a specified file into that subkey. This registration information is in the form of a hive. A hive is a discrete body of keys, subkeys, and values that is rooted at the top of the registry hierarchy. A hive is backed by a single file and .LOG file.

LONG RegLoadKey(
  HKEY hKey,        // handle to open key
  LPCTSTR lpSubKey, // subkey name
  LPCTSTR lpFile    // registry file name
);

Parameters

hKey
[in] Specifies the key where the subkey will be created. This can be a predefined reserved handle value, or a handle returned by a call to RegConnectRegistry. The predefined reserved handle values are:

HKEY_LOCAL_MACHINE
HKEY_USERS

This function always loads information at the top of the registry hierarchy. The HKEY_CLASSES_ROOT and HKEY_CURRENT_USER handle values cannot be specified for this parameter, because they represent subsets of the HKEY_LOCAL_MACHINE and HKEY_USERS handle values, respectively.

lpSubKey
[in] Pointer to a null-terminated string that specifies the name of the key to be created under hKey. This subkey is where the registration information from the file will be loaded.
lpFile
[in] Pointer to a null-terminated string containing the name of a file that has registry information. This file must have been created with the RegSaveKey function. If this file does not exist, a file is created with the specified name.

Windows 95/98/Me: RegLoadKey does not support long file names. If the desired file has a long file name, use the short file name to load it.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

If hKey is a handle returned by RegConnectRegistry, then the path specified in lpFile is relative to the remote computer.

Windows NT/2000 or later: The calling process must have the SE_RESTORE_NAME privilege. For more information about privileges, see Privileges.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegConnectRegistry, RegDeleteKey, RegReplaceKey, RegRestoreKey, RegSaveKey, RegUnloadKey


RegNotifyChangeKeyValue

The RegNotifyChangeKeyValue function notifies the caller about changes to the attributes or contents of a specified registry key. Note that the function does not notify the caller if the specified key is deleted.

LONG RegNotifyChangeKeyValue(
  HKEY hKey,             // handle to key to watch
  BOOL bWatchSubtree,    // subkey notification option
  DWORD dwNotifyFilter,  // changes to be reported
  HANDLE hEvent,         // handle to event to be signaled
  BOOL fAsynchronous     // asynchronous reporting option
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

bWatchSubtree
[in] Specifies a flag that indicates whether to report changes in the specified key and all of its subkeys or only in the specified key. If this parameter is TRUE, the function reports changes in the key and its subkeys. If the parameter is FALSE, the function reports changes only in the key.
dwNotifyFilter
[in] Specifies a set of flags that control which changes should be reported. This parameter can be a combination of the following values.
Value | Meaning
REG_NOTIFY_CHANGE_NAME | Notify the caller if a subkey is added or deleted.
REG_NOTIFY_CHANGE_ATTRIBUTES | Notify the caller of changes to the attributes of the key, such as the security descriptor information.
REG_NOTIFY_CHANGE_LAST_SET | Notify the caller of changes to a value of the key. This can include adding or deleting a value, or changing an existing value.
REG_NOTIFY_CHANGE_SECURITY | Notify the caller of changes to the security descriptor of the key.

hEvent
[in] Handle to an event. If the fAsynchronous parameter is TRUE, the function returns immediately and changes are reported by signaling this event. If fAsynchronous is FALSE, hEvent is ignored.
fAsynchronous
[in] Specifies a flag that indicates how the function reports changes. If this parameter is TRUE, the function returns immediately and reports changes by signaling the specified event. When this parameter is FALSE, the function does not return until a change has occurred.

If hEvent does not specify a valid event, the fAsynchronous parameter cannot be TRUE.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

If the key identified by the hKey parameter is closed, the event is signaled. This means that an application should not depend on the key being open after returning from a wait operation on the event.

If the thread that called RegNotifyChangeKeyValue exits, the event is signaled. When the event is signaled, RegNotifyChangeKeyValue ends its monitoring of the key value. If you want to monitor further changes in the value of the key, call RegNotifyChangeKeyValue again.

RegNotifyChangeKeyValue does not work with remote handles. If RegNotifyChangeKeyValue is called with an hKey value that is a remote handle, it returns ERROR_INVALID_HANDLE.

Windows 98/Me: No registry subkey or value name can exceed 255 characters.

If this function is called more than once with different values for the bWatchSubtree and dwNotifyFilter parameters, the changed parameter values will be ignored on subsequent calls. If you want to call RegNotifyChangeKeyValue again with different values for these parameters, you must first close the key handle hKey by calling CloseHandle, then reopen the key handle by calling RegOpenKeyEx.

The following program illustrates how to use RegNotifyChangeKeyValue.

#include <stdio.h>
#include <windows.h>

void main(int argc, char *argv[])
{
DWORD  dwFilter = REG_NOTIFY_CHANGE_NAME |
                  REG_NOTIFY_CHANGE_ATTRIBUTES |
                  REG_NOTIFY_CHANGE_LAST_SET |
                  REG_NOTIFY_CHANGE_SECURITY;

HANDLE hEvent;
HKEY   hMainKey;
HKEY   hKey;
LONG   lErrorCode;

// Display the usage error message.
if (argc != 3)
{
    printf("Usage: notify [HKLM/HKU/HKCU/HKCR/HCC] [subkey]\n");
    return;
}

// Convert parameters to appropriate handles.
if (strcmp("HKLM", argv[1]) == 0)
   hMainKey = HKEY_LOCAL_MACHINE;
else if (strcmp("HKU", argv[1]) == 0)
   hMainKey = HKEY_USERS;
else if (strcmp("HKCU", argv[1]) == 0)
   hMainKey = HKEY_CURRENT_USER;
else if (strcmp("HKCR", argv[1]) == 0)
   hMainKey = HKEY_CLASSES_ROOT;
else if (strcmp("HCC", argv[1]) == 0)
   hMainKey = HKEY_CURRENT_CONFIG;
else
{
    printf("Usage: notify [HKLM/HKU/HKCU/HKCR/HCC] [subkey]\n");
    return;
}

// Open a key.
lErrorCode = RegOpenKeyEx(hMainKey, argv[2], 0, KEY_NOTIFY, &hKey);
if (lErrorCode != ERROR_SUCCESS)
   printf("Error in RegOpenKeyEx.\n");

// Create an event.
hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (hEvent == NULL)
    printf("Error in CreateEvent.\n");

// Watch the registry key for a change of value.
lErrorCode = RegNotifyChangeKeyValue(hKey,
                                     TRUE,
                                     dwFilter,
                                     hEvent,
                                     TRUE);
if (lErrorCode != ERROR_SUCCESS)
   printf("Error in RegNotifyChangeKeyValue.\n");

// Wait for an event to occur.
if (WaitForSingleObject(hEvent, INFINITE) == WAIT_FAILED)
   printf("Error in WaitForSingleObject.\n");

// Close the key.
lErrorCode = RegCloseKey(hKey);
if (lErrorCode != ERROR_SUCCESS)
   printf("Error in RegCloseKey.\n");

// Close the handle.
if (!CloseHandle(hEvent))
   printf("Error in CloseHandle.\n");
}

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 98 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Registry Overview, Registry Functions, RegDeleteKey, RegEnumKey, RegEnumKeyEx, RegEnumValue, RegQueryInfoKey, RegQueryValue, RegQueryValueEx


RegOpenCurrentUser

The RegOpenCurrentUser function retrieves a handle to the HKEY_CURRENT_USER key for the user the current thread is impersonating.

LONG RegOpenCurrentUser(
  REGSAM samDesired,  // access rights
  PHKEY phkResult     // handle to open key
);

Parameters

samDesired
[in] An access mask that specifies the desired access rights to the key. This parameter can be a combination of the following values.
Value | Meaning
KEY_CREATE_LINK | Permission to create a symbolic link.
KEY_CREATE_SUB_KEY | Permission to create subkeys.
KEY_ENUMERATE_SUB_KEYS | Permission to enumerate subkeys.
KEY_EXECUTE | Permission for read access.
KEY_NOTIFY | Permission for change notification.
KEY_QUERY_VALUE | Permission to query subkey data.
KEY_SET_VALUE | Permission to set subkey data.
KEY_ALL_ACCESS | Combines the KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, KEY_CREATE_SUB_KEY, KEY_CREATE_LINK, and KEY_SET_VALUE access rights, plus all the standard access rights except SYNCHRONIZE.
KEY_READ | Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY access rights.
KEY_WRITE | Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.

phkResult
[out] Pointer to a variable that receives a handle to the opened key. When you no longer need the returned handle, call the RegCloseKey function to close it.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The HKEY_CURRENT_USER key is cached for all threads in a process. If the process is impersonating multiple users, RegOpenCurrentUser allows the threads to access the appropriate key.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Registry Overview, Registry Functions, RegCloseKey


RegOpenKey

The RegOpenKey function opens the specified registry key.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should use the RegOpenKeyEx function.

LONG RegOpenKey(
  HKEY hKey,        // handle to open key
  LPCTSTR lpSubKey, // name of subkey to open
  PHKEY phkResult   // handle to open key
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

The key opened by the RegOpenKey function is a subkey of the key identified by hKey.

lpSubKey
[in] Pointer to a null-terminated string containing the name of the key to open. This key must be a subkey of the key identified by the hKey parameter. If this parameter is NULL or a pointer to an empty string, the function returns the same handle that was passed in.
phkResult
[out] Pointer to a variable that receives a handle to the opened key. When you no longer need the returned handle, call the RegCloseKey function to close it.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The RegOpenKey function uses the default security access mask to open a key. If opening the key requires a different mask, the function fails, returning ERROR_ACCESS_DENIED. An application should use the RegOpenKeyEx function to specify an access mask in this situation.

Unlike the RegCreateKey function, RegOpenKey does not create the specified key if the key does not exist in the database.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCloseKey, RegCreateKey, RegCreateKeyEx, RegDeleteKey, RegOpenKeyEx


RegOpenKeyEx

The RegOpenKeyEx function opens the specified registry key.

LONG RegOpenKeyEx(
  HKEY hKey,         // handle to open key
  LPCTSTR lpSubKey,  // subkey name
  DWORD ulOptions,   // reserved
  REGSAM samDesired, // security access mask
  PHKEY phkResult    // handle to open key
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

lpSubKey
[in] Pointer to a null-terminated string containing the name of the subkey to open. If this parameter is NULL or a pointer to an empty string, the function will open a new handle to the key identified by the hKey parameter. In this case, the function will not close the handles previously opened.
ulOptions
Reserved; must be zero.
samDesired
[in] An access mask that specifies the desired access rights to the key. This parameter can be a combination of the following values.
Value | Meaning
KEY_CREATE_LINK | Permission to create a symbolic link.
KEY_CREATE_SUB_KEY | Permission to create subkeys.
KEY_ENUMERATE_SUB_KEYS | Permission to enumerate subkeys.
KEY_EXECUTE | Permission for read access.
KEY_NOTIFY | Permission for change notification.
KEY_QUERY_VALUE | Permission to query subkey data.
KEY_SET_VALUE | Permission to set subkey data.
KEY_ALL_ACCESS | Combines the KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, KEY_CREATE_SUB_KEY, KEY_CREATE_LINK, and KEY_SET_VALUE access rights, plus all the standard access rights except SYNCHRONIZE.
KEY_READ | Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY access rights.
KEY_WRITE | Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.

phkResult
[out] Pointer to a variable that receives a handle to the opened key. When you no longer need the returned handle, call the RegCloseKey function to close it.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

Unlike the RegCreateKeyEx function, the RegOpenKeyEx function does not create the specified key if the key does not exist in the registry.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

For example, see Getting the System Version.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCloseKey, RegCreateKeyEx, RegDeleteKey, RegOpenKey


RegOpenUserClassesRoot

The RegOpenUserClassesRoot function retrieves a handle to the HKEY_CLASSES_ROOT key for a specified user. The user is identified by an access token. The returned key has a view of the registry that merges the contents of the HKEY_LOCAL_MACHINE\Software\Classes key with the contents of the Software\Classes keys in the user's registry hive. For more information, see The HKEY_CLASSES_ROOT Key.

LONG RegOpenUserClassesRoot(
  HANDLE hToken,      // token
  DWORD  dwOptions,   // reserved; must be zero
  REGSAM samDesired,  // security access mask
  PHKEY  phkResult    // receives key handle
);

Parameters

hToken
[in] Handle to a primary or impersonation access token that identifies the user of interest. This can be a token handle returned by a call to LogonUser, CreateRestrictedToken, DuplicateToken, DuplicateTokenEx, OpenProcessToken, or OpenThreadToken functions. The handle must have TOKEN_QUERY access.
dwOptions
Reserved; must be zero.
samDesired
[in] An access mask that specifies the desired access rights to the key. This parameter can be a combination of the following values.
Value | Meaning
KEY_CREATE_LINK | Permission to create a symbolic link.
KEY_CREATE_SUB_KEY | Permission to create subkeys.
KEY_ENUMERATE_SUB_KEYS | Permission to enumerate subkeys.
KEY_EXECUTE | Permission for read access.
KEY_NOTIFY | Permission for change notification.
KEY_QUERY_VALUE | Permission to query subkey data.
KEY_SET_VALUE | Permission to set subkey data.
KEY_ALL_ACCESS | Combines the KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, KEY_CREATE_SUB_KEY, KEY_CREATE_LINK, and KEY_SET_VALUE access rights, plus all the standard access rights except SYNCHRONIZE.
KEY_READ | Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY access rights.
KEY_WRITE | Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.

phkResult
[out] Pointer to a variable that receives a handle to the opened key. When you no longer need the returned handle, call the RegCloseKey function to close it.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The RegOpenUserClassesRoot function enables you to retrieve the merged HKEY_CLASSES_ROOT information for users other than the interactive user. For example, the server component of a client/server application could use RegOpenUserClassesRoot to retrieve the merged information for a client.

RegOpenUserClassesRoot fails if the user profile for the specified user is not loaded. When a user logs on interactively, the system automatically loads the user's profile. For other users, you can call the LoadUserProfile function to load the user's profile. However, LoadUserProfile can be very time-consuming, so do not call it for this purpose unless it is absolutely necessary to have the user's merged HKEY_CLASSES_ROOT information.

Applications running in the security context of the interactively logged-on user do not need to use RegOpenUserClassesRoot. These applications can call the RegOpenKeyEx function to retrieve a merged view of the HKEY_CLASSES_ROOT key for the interactive user.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Registry Overview, Registry Functions, LoadUserProfile, RegCloseKey, RegOpenKeyEx


RegOverridePredefKey

The RegOverridePredefKey function maps a predefined registry key to the specified registry key.

LONG RegOverridePredefKey(
  HKEY hKey,     // predefined handle to key
  HKEY hNewHKey  // new handle to key
);

Parameters

hKey
[in] Handle to one of the following predefined reserved registry key handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
HKEY_PERFORMANCE_DATA

hNewHKey
[in] Handle to a key that is predefined or currently open. RegOverridePredefKey remaps hKey to refer to the hNewHKey key. This redirection applies only to the process that calls RegOverridePredefKey.

If hNewHKey is NULL, the function restores the default mapping of the predefined key.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The RegOverridePredefKey function is intended for software installation programs. It allows them to remap a predefined key, load a DLL component that will be installed on the system, call an entry point in the DLL, and examine the changes to the registry that the component attempted to make. The installation program can then write those changes to the locations intended by the DLL, or make changes to the data before writing it.

For example, consider an installation program that installs an ActiveX control as part of an application installation. The installation program needs to call the control's DllRegisterServer entry point to enable the control to register itself. Before this call, the installation program can call RegOverridePredefKey to remap HKEY_CLASSES_ROOT to a temporary key such as HKEY_CURRENT_USER\TemporaryInstall\DllRegistration. It then calls DllRegisterServer, which causes the ActiveX control to write its registry entries to the temporary key. The installation program then calls RegOverridePredefKey again to restore the original mapping of HKEY_CLASSES_ROOT. The installation program can modify the keys written to the temporary key, if necessary, before copying them to the original HKEY_CLASSES_ROOT.

After the call to RegOverridePredefKey, you can safely call RegCloseKey to close the hNewHKey handle. The system maintains its own reference to hNewHKey.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.

See Also

Registry Overview, Registry Functions, DllRegisterServer


RegQueryInfoKey

The RegQueryInfoKey function retrieves information about the specified registry key.

LONG RegQueryInfoKey(
  HKEY hKey,                      // handle to key
  LPTSTR lpClass,                 // class buffer
  LPDWORD lpcClass,               // size of class buffer
  LPDWORD lpReserved,             // reserved
  LPDWORD lpcSubKeys,             // number of subkeys
  LPDWORD lpcMaxSubKeyLen,        // longest subkey name
  LPDWORD lpcMaxClassLen,         // longest class string
  LPDWORD lpcValues,              // number of value entries
  LPDWORD lpcMaxValueNameLen,     // longest value name
  LPDWORD lpcMaxValueLen,         // longest value data
  LPDWORD lpcbSecurityDescriptor, // descriptor length
  PFILETIME lpftLastWriteTime     // last write time
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

lpClass
[out] Pointer to a buffer that receives the null-terminated class string of the key. No classes are currently defined; applications should ignore this parameter. This parameter can be NULL.
lpcClass
[in/out] Pointer to a variable that specifies the size, in TCHARs, of the buffer pointed to by the lpClass parameter. This size should include the terminating null character. When the function returns, this variable contains the length of the class string stored in the buffer. The count returned does not include the terminating null character. If the buffer is not big enough, the function returns ERROR_MORE_DATA, and the variable contains the size of the string, in characters, without counting the null character.

If lpClass is NULL, lpcClass can be NULL.

Windows NT/2000 or later: If the lpClass parameter is a valid address, but the lpcClass parameter is not (for example, it is NULL), the function returns ERROR_INVALID_PARAMETER.

Windows 95/98/Me: If the lpClass parameter is a valid address, but the lpcClass parameter is not (for example, it is NULL), the function returns ERROR_SUCCESS instead of ERROR_INVALID_PARAMETER. To ensure compatibility with other platforms, verify that lpcClass is valid before calling the function.

lpReserved
Reserved; must be NULL.
lpcSubKeys
[out] Pointer to a variable that receives the number of subkeys contained by the specified key. This parameter can be NULL.
lpcMaxSubKeyLen
[out] Pointer to a variable that receives the length, in TCHARs, of the key's subkey with the longest name. This parameter can be NULL.

Windows NT/2000 or later: The length does not include the terminating null character.

Windows 95/98/Me: The length includes the terminating null character.

lpcMaxClassLen
[out] Pointer to a variable that receives the length, in TCHARs, of the longest string specifying a subkey class. The count returned does not include the terminating null character. This parameter can be NULL.
lpcValues
[out] Pointer to a variable that receives the number of values associated with the key. This parameter can be NULL.
lpcMaxValueNameLen
[out] Pointer to a variable that receives the length, in TCHARs, of the key's longest value name. The length does not include the terminating null character. This parameter can be NULL.
lpcMaxValueLen
[out] Pointer to a variable that receives the length, in bytes, of the longest data component among the key's values. This parameter can be NULL.
lpcbSecurityDescriptor
[out] Pointer to a variable that receives the length, in bytes, of the key's security descriptor. This parameter can be NULL.
lpftLastWriteTime
[out] Pointer to a FILETIME structure that receives the last write time. This parameter can be NULL.

Windows NT/2000 or later: The function sets the members of the FILETIME structure to indicate the last time that the key or any of its value entries was modified.

Windows 95/98/Me: The function sets the members of the FILETIME structure to zero. This is because the system does not keep track of registry key last write time information.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The key identified by the hKey parameter must have been opened with KEY_QUERY_VALUE access (KEY_READ access includes KEY_QUERY_VALUE access).

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

For example, see Displaying Object, Instance, and Counter Names.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, FILETIME, RegDeleteKey, RegEnumKey, RegEnumKeyEx, RegEnumValue, RegQueryValue, RegQueryValueEx


RegQueryMultipleValues

The RegQueryMultipleValues function retrieves the type and data for a list of value names associated with an open registry key.

LONG RegQueryMultipleValues(
  HKEY hKey,         // handle to key to query
  PVALENT val_list,  // array of value entries
  DWORD num_vals,    // size of array
  LPTSTR lpValueBuf, // value information buffer
  LPDWORD ldwTotsize // size of value information buffer
);

Parameters

hKey
[in] Handle to a currently open key or any of the pre-defined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

val_list
[out] Pointer to an array of VALENT structures that describe one or more value entries. On input, the ve_valuename member of each structure must contain a pointer to the name of a value to retrieve. The function fails if any of the specified values do not exist in the specified key.

If the function succeeds, each element of the array contains the information for the specified value.

num_vals
[in] Specifies the number of elements in the val_list array.
lpValueBuf
[out] Pointer to a buffer. If the function succeeds, the buffer receives the data for each value.

If lpValueBuf is NULL, the function returns success, and ldwTotsize returns the required size, in bytes, of the buffer.

ldwTotsize
[in/out] Pointer to a variable that specifies the size, in bytes, of the buffer pointed to by the lpValueBuf parameter. If the function succeeds, ldwTotsize receives the number of bytes copied to the buffer. If the function fails because the buffer is too small, ldwTotsize receives the required size, in bytes.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is one of the following error codes.

Value | Meaning
ERROR_CANTREAD | RegQueryMultipleValues cannot instantiate or access the provider of the dynamic key.
ERROR_MORE_DATA | The buffer pointed to by lpValueBuf was too small. In this case, ldwTotsize returns the required buffer size.
ERROR_TRANSFER_TOO_LONG | The total length of the requested data (size of the val_list array + ldwTotSize) is more than the system limit of one megabyte.

Remarks

The RegQueryMultipleValues function allows an application to query one or more values of a static or dynamic key. If the target key is a static key, the system provides all of the values in an atomic fashion. To prevent excessive serialization, the aggregate data returned by the function cannot exceed one megabyte.

If the target key is a dynamic key, its provider must provide all the values in an atomic fashion. This means the provider should fill the results buffer synchronously, providing a consistent view of all the values in the buffer while avoiding excessive serialization. The provider can provide at most one megabyte of total output data during an atomic call to this function.

RegQueryMultipleValues is supported remotely; that is, the hKey parameter passed to the function can refer to a remote computer.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, VALENT


RegQueryValue

The RegQueryValue function retrieves the data associated with the default or unnamed value of a specified registry key. The data must be a null-terminated string.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should use the RegQueryValueEx function.

LONG RegQueryValue(
  HKEY hKey,        // handle to key to query
  LPCTSTR lpSubKey, // subkey name
  LPTSTR lpValue,   // string buffer
  PLONG lpcbValue   // size of returned string
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

lpSubKey
[in] Pointer to a null-terminated string containing the name of the subkey of the hKey parameter for which the default value is retrieved. If this parameter is NULL or points to an empty string, the function retrieves the default value for the key identified by hKey.
lpValue
[out] Pointer to a buffer that receives the null-terminated string associated with the default value of the specified key.

If lpValue is NULL, and lpcbValue is non-NULL, the function returns ERROR_SUCCESS, and stores the size of the data, in bytes, in the variable pointed to by lpcbValue. This lets an application determine the best way to allocate a buffer for the value's data.

lpcbValue
[in/out] Pointer to a variable that specifies the size, in bytes, of the buffer pointed to by the lpValue parameter. When the function returns, this variable contains the size of the data copied to lpValue, including the terminating null character.

If the buffer specified by lpValue parameter is not large enough to hold the data, the function returns the value ERROR_MORE_DATA, and stores the required buffer size, in bytes, into the variable pointed to by lpcbValue. In this case, the contents of the lpValue buffer are undefined.

In all cases the value returned in lpcbValue includes the size of the terminating null character in the string.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The key identified by the hKey parameter must have been opened with KEY_QUERY_VALUE access (KEY_READ access includes KEY_QUERY_VALUE access).

If the ANSI version of this function is used (either by explicitly calling RegQueryValueA or by not defining UNICODE before including the Windows.h file), this function converts the stored Unicode string to an ANSI string before copying it to the buffer specified by the lpValue parameter.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegEnumKey, RegEnumKeyEx, RegEnumValue, RegQueryInfoKey, RegQueryValueEx, RegSetValue, RegSetValueEx


RegQueryValueEx

The RegQueryValueEx function retrieves the type and data for a specified value name associated with an open registry key.

LONG RegQueryValueEx(
  HKEY hKey,            // handle to key
  LPCTSTR lpValueName,  // value name
  LPDWORD lpReserved,   // reserved
  LPDWORD lpType,       // type buffer
  LPBYTE lpData,        // data buffer
  LPDWORD lpcbData      // size of data buffer
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

lpValueName
[in] Pointer to a null-terminated string containing the name of the value to query.

If lpValueName is NULL or an empty string, "", the function retrieves the type and data for the key's unnamed or default value, if any.

Windows 95/98/Me: Every key has a default value that initially does not contain data. On Windows 95, the default value type is always REG_SZ. On Windows 98, the type of a key's default value is initially REG_SZ, but RegSetValueEx can specify a default value with a different type.

Windows NT/2000 or later: Keys do not automatically have an unnamed or default value. Unnamed values can be of any type.

lpReserved
Reserved; must be NULL.
lpType
[out] Pointer to a variable that receives a code indicating the type of data stored in the specified value. For a list of the possible type codes, see Registry Value Types. The lpType parameter can be NULL if the type code is not required.
lpData
[in, out] Pointer to a buffer that receives the value's data. This parameter can be NULL if the data is not required.
lpcbData
[in/out] Pointer to a variable that specifies the size, in bytes, of the buffer pointed to by the lpData parameter. When the function returns, this variable contains the size of the data copied to lpData.

If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, then lpcbData will also include the size of the terminating null character or characters.

The lpcbData parameter can be NULL only if lpData is NULL.

If the buffer specified by lpData parameter is not large enough to hold the data, the function returns the value ERROR_MORE_DATA, and stores the required buffer size, in bytes, into the variable pointed to by lpcbData. In this case, the contents of the lpValue buffer are undefined.

If lpData is NULL, and lpcbData is non-NULL, the function returns ERROR_SUCCESS, and stores the size of the data, in bytes, in the variable pointed to by lpcbData. This lets an application determine the best way to allocate a buffer for the value's data.

Window NT: If hKey specifies HKEY_PERFORMANCE_DATA and the lpData buffer is too small, RegQueryValueEx returns ERROR_MORE_DATA but lpcbData does not return the required buffer size. This is because the size of the performance data can change from one call to the next. In this case, you must increase the buffer size and call RegQueryValueEx again passing the updated buffer size in the lpcbData parameter. Repeat this until the function succeeds. You need to maintain a separate variable to keep track of the buffer size, because the value returned by lpcbData is unpredictable.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The key identified by hKey must have been opened with KEY_QUERY_VALUE access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, the string may not have been stored with the proper null-terminating characters. Applications should ensure that the string is properly terminated before using it, otherwise, the application may fail by overwriting a buffer.

If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, and the ANSI version of this function is used (either by explicitly calling RegQueryValueExA or by not defining UNICODE before including the Windows.h file), this function converts the stored Unicode string to an ANSI string before copying it to the buffer pointed to by lpData.

Window NT/2000: When calling the RegQueryValueEx function with hKey set to the HKEY_PERFORMANCE_DATA handle and a value string of a specified object, the returned data structure sometimes has unrequested objects. Don't be surprised; this is normal behavior. When calling the RegQueryValueEx function, you should always expect to walk the returned data structure to look for the requested object.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

For example, see Retrieving Data from the Registry.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, ExpandEnvironmentStrings, RegCreateKeyEx, RegEnumKey, RegEnumKeyEx, RegEnumValue, RegOpenKeyEx, RegQueryInfoKey, RegQueryValue


RegReplaceKey

The RegReplaceKey function replaces the file backing a registry key and all its subkeys with another file, so that when the system is next started, the key and subkeys will have the values stored in the new file.

LONG RegReplaceKey(
  HKEY hKey,         // handle to open key
  LPCTSTR lpSubKey,  // subkey name
  LPCTSTR lpNewFile, // data file
  LPCTSTR lpOldFile  // backup file
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpSubKey
[in] Pointer to a null-terminated string containing the name of the key whose subkeys and values are replaced by this function. This key must be a subkey of the key identified by the hKey parameter. This parameter can be NULL.

If the specified subkey is not the root of a hive, RegReplaceKey traverses up the hive tree structure until it encounters a hive root, then it replaces the contents of that hive with the contents of the data file specified by lpNewFile.

lpNewFile
[in] Pointer to a null-terminated string containing the name of the file with registration information. This file is typically created by using the RegSaveKey function.
lpOldFile
[in] Pointer to a null-terminated string containing the name of a file that receives a backup copy of the registry information being replaced.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

The file specified by the lpNewFile parameter remains open until the system is restarted.

If hKey is a handle returned by RegConnectRegistry, then the paths specified in lpNewFile and lpOldFile are relative to the remote computer.

Windows NT/2000 or later: The calling process must have the SE_RESTORE_NAME privilege. For more information about privileges, see Privileges.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegConnectRegistry, RegDeleteKey, RegLoadKey, RegRestoreKey, RegSaveKey


RegRestoreKey

The RegRestoreKey function reads the registry information in a specified file and copies it over the specified key. This registry information may be in the form of a key and multiple levels of subkeys.

LONG RegRestoreKey(
  HKEY hKey,      // handle to key where restore begins
  LPCTSTR lpFile, // registry file
  DWORD dwFlags   // options
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

Any information contained in this key and its descendent keys is overwritten by the information in the file pointed to by the lpFile parameter.

lpFile
[in] Pointer to a null-terminated string containing the name of the file with registry information. This file is typically created by using the RegSaveKey function.
dwFlags
[in] Flag indicating how the key or keys are to be restored. This parameter can be one of the following values.
Value | Meaning
REG_FORCE_RESTORE | If specified, the restore operation is executed even if open handles exist at or beneath the location in the registry hierarchy the hKey parameter points to.
REG_NO_LAZY_FLUSH | If specified, the key or hive specified by the hKey parameter will not be lazy flushed, or flushed automatically and regularly after an interval of time.
REG_REFRESH_HIVE | If specified, the location of the hive the hKey parameter points to will be restored to its state immediately following the last flush. The hive must not be lazy flushed (by calling RegRestoreKey with REG_NO_LAZY_FLUSH specified as the value of this parameter), the caller must have TCB privilege, and the handle the hKey parameter refers to must point to the root of the hive.
REG_WHOLE_HIVE_VOLATILE | If specified, a new, volatile (memory only) set of registry information, or hive, is created. If REG_WHOLE_HIVE_VOLATILE is specified, the key identified by the hKey parameter must be either the HKEY_USERS or HKEY_LOCAL_MACHINE value.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

If any subkeys of the hKey parameter are open, RegRestoreKey fails. The function also fails if the calling process does not have the SE_RESTORE_NAME privilege. For more information about privileges, see Privileges.

This function replaces the keys and values below the specified key with the keys and values that are subsidiary to the top-level key in the file, no matter what the name of the top-level key in the file might be. For example, hKey might identify a key A with subkeys B and C, while the lpFile parameter specifies a file containing key X with subkeys Y and Z. After a call to RegRestoreKey, the registry would contain key A with subkeys Y and Z. The value entries of A would be replaced by the value entries of X.

The new information in the file specified by lpFile overwrites the contents of the key specified by the hKey parameter, except for the key name.

If hKey represents a key in a remote computer, the path described by lpFile is relative to the remote computer.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegDeleteKey, RegLoadKey, RegReplaceKey, RegSaveKey


RegSaveKey

The RegSaveKey function saves the specified key and all of its subkeys and values to a new file.

LONG RegSaveKey(
  HKEY hKey,                                  // handle to key
  LPCTSTR lpFile,                             // data file
  LPSECURITY_ATTRIBUTES lpSecurityAttributes  // SD
);

Parameters

hKey
[in] Specifies a handle to the key where the save operation is to begin, or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS

lpFile
[in] Pointer to a null-terminated string containing the name of the file in which the specified key and subkeys are saved.

Windows 95/98/Me: RegSaveKey does not support long file names. To save a registry hive to a file with a long file name, first save the hive to a short file name, then rename the resulting file to its long file name.

Windows NT/2000 or later: If the string does not include a path, the file is created in the current directory of the calling process for a local key, or in the %systemroot%\system32 directory for a remote key.

Windows 95/98/Me: If the string does not include a path, the file is created in the Windows root directory for local and remote keys. See GetWindowsDirectory.

lpSecurityAttributes
Windows NT/2000 or later: [in] Pointer to a SECURITY_ATTRIBUTES structure that specifies a security descriptor for the new file. If lpSecurityAttributes is NULL, the file gets a default security descriptor.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Windows NT/2000 or later: If the file already exists, the function fails with the ERROR_ALREADY_EXISTS error.

Windows 95/98/Me: If the file already exists, the function fails with the ERROR_REGISTRY_IO_FAILED error.

Remarks

If hKey represents a key on a remote computer, the path described by lpFile is relative to the remote computer.

The RegSaveKey function saves only nonvolatile keys. It does not save volatile keys. A key is made volatile or nonvolatile at its creation; see RegCreateKeyEx.

You can use the file created by RegSaveKey in subsequent calls to the RegLoadKey, RegReplaceKey, or RegRestoreKey functions. If RegSaveKey fails part way through its operation, the file will be corrupt and subsequent calls to RegLoadKey, RegReplaceKey, or RegRestoreKey for the file will fail.

Windows NT/2000 or later: The new file has the archive attribute.

Windows 95/98/Me: The new file has the archive, hidden, read-only, and system attributes.

Windows NT/2000 or later: The calling process must have the SE_BACKUP_NAME privilege enabled. For more information about privileges, see Privileges.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCreateKeyEx, RegDeleteKey, RegLoadKey, RegReplaceKey, RegRestoreKey, SECURITY_ATTRIBUTES


RegSetValue

The RegSetValue function sets the data for the default or unnamed value of a specified registry key. The data must be a text string.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should use the RegSetValueEx function.

LONG RegSetValue(
  HKEY hKey,         // handle to key
  LPCTSTR lpSubKey,  // subkey name
  DWORD dwType,      // information type
  LPCTSTR lpData,    // value data
  DWORD cbData       // size of value data
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

lpSubKey
[in] Pointer to a null-terminated string containing the name of a subkey of the hKey parameter. The function sets the default value of the specified subkey. If this parameter is NULL or points to an empty string, the function sets the default value of the key identified by hKey.
dwType
[in] Specifies the type of information to be stored. This parameter must be the REG_SZ type. To store other data types, use the RegSetValueEx function.
lpData
[in] Pointer to a null-terminated string containing the data to set for the default value of the specified key.
cbData
[in] Specifies the length, in bytes, of the string pointed to by the lpData parameter, not including the terminating null character.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

If the key specified by the lpSubKey parameter does not exist, the RegSetValue function creates it.

Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the file names stored in the registry. This helps the registry perform efficiently.

The key identified by the hKey parameter must have been opened with KEY_SET_VALUE access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function. If the ANSI version of this function is used (either by explicitly calling RegSetValueA or by not defining UNICODE before including the Windows.h file), the lpData parameter must be an ANSI character string. The string is converted to Unicode before it is stored in the registry.

Windows 95/98/Me: No registry subkey or value name can exceed 255 characters.

Windows 95/98/Me: The maximum size of a single registry value is 16,300 bytes. This limit includes the size of the data (cbData).

Windows 95/98/Me: There is a 64K limit for the total size of all values of a key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCreateKeyEx, RegFlushKey, RegOpenKeyEx, RegQueryValue, RegQueryValueEx, RegSetValueEx


RegSetValueEx

The RegSetValueEx function sets the data and type of a specified value under a registry key.

LONG RegSetValueEx(
  HKEY hKey,           // handle to key
  LPCTSTR lpValueName, // value name
  DWORD Reserved,      // reserved
  DWORD dwType,        // value type
  CONST BYTE *lpData,  // value data
  DWORD cbData         // size of value data
);

Parameters

hKey
[in] Handle to a currently open key or any of the following predefined reserved handle values:

HKEY_CLASSES_ROOT
HKEY_CURRENT_CONFIG
HKEY_CURRENT_USER
HKEY_LOCAL_MACHINE
HKEY_USERS
Windows NT/2000 or later: HKEY_PERFORMANCE_DATA
Windows 95/98/Me: HKEY_DYN_DATA

lpValueName
[in] Pointer to a string containing the name of the value to set. If a value with this name is not already present in the key, the function adds it to the key.

If lpValueName is NULL or an empty string, "", the function sets the type and data for the key's unnamed or default value.

Windows 95/98/Me: On Windows 95, the type of a key's default value is always REG_SZ, so the dwType parameter must specify REG_SZ for an unnamed value. On Windows 98/Me, an unnamed value can be of any type.

Windows NT/2000 or later: Registry keys do not have default values, but they can have one unnamed value, which can be of any type.

Reserved
Reserved; must be zero.
dwType
[in] Specifies a code indicating the type of data pointed to by the lpData parameter. For a list of the possible type codes, see Registry Value Types.
lpData
[in] Pointer to a buffer containing the data to be stored with the specified value name. For string-based data types, such as REG_SZ, the string must be NULL-terminated. With the REG_MULTI_SZ data type, the string must be double-NULL terminated.
cbData
[in] Specifies the size of the information pointed to by the lpData parameter, in bytes. If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character or characters.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the file names stored in the registry. This helps the registry perform efficiently. Application elements such as icons, bitmaps, and executable files should be stored as files and not be placed in the registry.

The key identified by the hKey parameter must have been opened with KEY_SET_VALUE access. To open the key, use the RegCreateKeyEx or RegOpenKeyEx function.

If dwType is the REG_SZ, REG_MULTI_SZ, or REG_EXPAND_SZ type and the ANSI version of this function is used (either by explicitly calling RegSetValueExA or by not defining UNICODE before including the Windows.h file), the data pointed to by the lpData parameter must be an ANSI character string. The string is converted to Unicode before it is stored in the registry.

Windows 95/98/Me: The maximum size of a single registry value is 16,300 bytes. This limit includes the size of the data (cbData) and the size of the value name (lpValueName).

Windows 95/98/Me: There is a 64K limit for the total size of all values of a key.

For example, see Adding a Source to the Registry.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegCreateKeyEx, RegFlushKey, RegOpenKeyEx, RegQueryValue, RegQueryValueEx, RegSetValue


RegUnLoadKey

The RegUnLoadKey function unloads the specified registry key and its subkeys from the registry.

LONG RegUnLoadKey(
  HKEY hKey,         // handle to open key
  LPCTSTR lpSubKey   // subkey name
);

Parameters

hKey
[in] Specifies the key to be unloaded. This can be a predefined reserved handle value, or a handle returned by a call to RegConnectRegistry. The predefined reserved handle values are:

HKEY_LOCAL_MACHINE
HKEY_USERS

lpSubKey
[in] Pointer to a null-terminated string containing the name of the subkey to be unloaded. The key referred to by the lpSubKey parameter must have been created by using the RegLoadKey function.

Return Values

If the function succeeds, the return value is ERROR_SUCCESS.

If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

Remarks

This function removes a hive from the registry but does not modify the file containing the registry information. A hive is a discrete body of keys, subkeys, and values that is rooted at the top of the registry hierarchy.

Windows NT/2000 or later: The calling process must have the SE_RESTORE_NAME privilege. For more information about privileges, see Privileges.

Windows 95/98/Me: No registry subkey or value name may exceed 255 characters.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, RegConnectRegistry, RegDeleteKey, RegLoadKey, RegRestoreKey


WritePrivateProfileSection

The WritePrivateProfileSection function replaces the keys and values for the specified section in an initialization file.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should store initialization information in the registry.

BOOL WritePrivateProfileSection(
  LPCTSTR lpAppName,  // section name
  LPCTSTR lpString,   // data
  LPCTSTR lpFileName  // file name
);

Parameters

lpAppName
[in] Pointer to a null-terminated string specifying the name of the section in which data is written. This section name is typically the name of the calling application.
lpString
[in] Pointer to a buffer containing the new key names and associated values that are to be written to the named section.
lpFileName
[in] Pointer to a null-terminated string containing the name of the initialization file. If this parameter does not contain a full path for the file, the function searches the Windows directory for the file. If the file does not exist and lpFileName does not contain a full path, the function creates the file in the Windows directory. The function does not create a file if lpFileName contains the full path and file name of a file that does not exist.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

The data in the buffer pointed to by the lpString parameter consists of one or more null-terminated strings, followed by a final null character. Each string has the following form:

key=string

The WritePrivateProfileSection function is not case-sensitive; the string pointed to by the lpAppName parameter can be a combination of uppercase and lowercase letters.

If no section name matches the string pointed to by the lpAppName parameter, WritePrivateProfileSection creates the section at the end of the specified initialization file and initializes the new section with the specified key name and value pairs.

WritePrivateProfileSection deletes the existing keys and values for the named section and inserts the key names and values in the buffer pointed to by the lpString parameter. The function does not attempt to correlate old and new key names; if the new names appear in a different order from the old names, any comments associated with preexisting keys and values in the initialization file will probably be associated with incorrect keys and values.

This operation is atomic; no operations that read from or write to the specified initialization file are allowed while the information is being written.

Windows 95/98/Me: The system keeps a cached version of Win.ini to improve performance. If all three parameters are NULL, the function flushes the cache. The function always returns FALSE after flushing the cache, regardless of whether the flush succeeds or fails.

Windows NT/2000 or later: The system maps most .ini file references to the registry, using the mapping defined under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

This mapping is likely if an application modifies system-component initialization files, such as Control.ini, System.ini, and Winfile.ini. In this case, the WritePrivateProfileSection function writes information to the registry, not to the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetPrivateProfileSection, RegCreateKeyEx, RegSetValueEx, WriteProfileSection


WritePrivateProfileString

The WritePrivateProfileString function copies a string into the specified section of an initialization file.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should store initialization information in the registry.

BOOL WritePrivateProfileString(
  LPCTSTR lpAppName,  // section name
  LPCTSTR lpKeyName,  // key name
  LPCTSTR lpString,   // string to add
  LPCTSTR lpFileName  // initialization file
);

Parameters

lpAppName
[in] Pointer to a null-terminated string containing the name of the section to which the string will be copied. If the section does not exist, it is created. The name of the section is case-independent; the string can be any combination of uppercase and lowercase letters.
lpKeyName
[in] Pointer to the null-terminated string containing the name of the key to be associated with a string. If the key does not exist in the specified section, it is created. If this parameter is NULL, the entire section, including all entries within the section, is deleted.
lpString
[in] Pointer to a null-terminated string to be written to the file. If this parameter is NULL, the key pointed to by the lpKeyName parameter is deleted.

Windows 95/98/Me: The system does not support the use of the TAB (\t) character as part of this parameter.

lpFileName
[in] Pointer to a null-terminated string that specifies the name of the initialization file.

Return Values

If the function successfully copies the string to the initialization file, the return value is nonzero.

If the function fails, or if it flushes the cached version of the most recently accessed initialization file, the return value is zero. To get extended error information, call GetLastError.

Remarks

Windows 95/98/Me: The system keeps a cached version of Win.ini to improve performance. If all three parameters are NULL, the function flushes the cache. The function always returns FALSE after flushing the cache, regardless of whether the flush succeeds or fails.

A section in the initialization file must have the following form:

[section]
key=string
      .
      .
      .

If the lpFileName parameter does not contain a full path and file name for the file, WritePrivateProfileString searches the Windows directory for the file. If the file does not exist, this function creates the file in the Windows directory.

If lpFileName contains a full path and file name and the file does not exist, WritePrivateProfileString creates the file. The specified directory must already exist.

Windows NT/2000 or later: The system maps most .ini file references to the registry, using the mapping defined under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

Windows NT/Windows 2000 keeps a cache for the IniFileMapping registry key. Calling WritePrivateProfileStringW with the value of all arguments set to NULL will cause the system to refresh its cache of the IniFileMappingKey for the specified .ini file.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

An application using the WritePrivateProfileStringW function to enter .ini file information into the registry should follow these guidelines:

  • Ensure that no .ini file of the specified name exists on the system.
  • Ensure that there is a key entry in the registry that specifies the .ini file. This entry should be under the path HKEY_LOCAL_MACHINE\SOFTWARE \Microsoft\Windows NT\CurrentVersion\IniFileMapping.
  • Specify a value for that .ini file key entry that specifies a section. That is to say, an application must specify a section name, as it would appear within an .ini file or registry entry. Here is an example: [My Section].
  • For system files, specify SYS for an added value.
  • For application files, specify USR within the added value. Here is an example: "My Section: USR: App Name\Section". And, since USR indicates a mapping under HKEY_CURRENT_USER, the application should also create a key under HKEY_CURRENT_USER that specifies the application name listed in the added value. For the example just given, that would be "App Name".
  • After following the preceding steps, an application setup program should call WritePrivateProfileStringW with the first three parameters set to NULL, and the fourth parameter set to the INI file name. For example:
    WritePrivateProfileStringW( NULL, NULL, NULL, L"appname.ini" );
  • Such a call causes the mapping of an .ini file to the registry to take effect before the next system reboot. The system rereads the mapping information into shared memory. A user will not have to reboot their computer after installing an application in order to have future invocations of the application see the mapping of the .ini file to the registry.

The following sample code illustrates the preceding guidelines and is based on several assumptions:

  • There is an application named App Name.
  • That application uses an .ini file named AppName.ini.
  • There is a section in the .ini file that we want to look like this:
    [Section1]
  FirstKey = It all worked out okay.
  SecondKey = By golly, it works.
  ThirdKey = Another test.
  • The user will not have to reboot the system in order to have future invocations of the application see the mapping of the .ini file to the registry.

Here is the sample code :

// include files
#include <stdio.h>
#include <windows.h>

// a main function
main()

{
  // local variables
  CHAR inBuf[80];
  HKEY  hKey1, hKey2;
  DWORD  dwDisposition;
  LONG   lRetCode;

  // try to create the .ini file key
  lRetCode = RegCreateKeyEx ( HKEY_LOCAL_MACHINE,
                              "SOFTWARE\\Microsoft\\Windows NT
                               \\CurrentVersion\\IniFileMapping\\appname.ini",
                              0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE,
                              NULL, &hKey1,
                              &dwDisposition);

  // if we failed, note it, and leave
  if (lRetCode != ERROR_SUCCESS){
    printf ("Error in creating appname.ini key\n");
    return (0) ;
    }

  // try to set a section value
  lRetCode = RegSetValueEx ( hKey1,
                             "Section1",
                             0,
                             REG_SZ,
                             "USR:App Name\\Section1",
                             20);

  // if we failed, note it, and leave
  if (lRetCode != ERROR_SUCCESS) {
    printf ( "Error in setting Section1 value\n");
    return (0) ;
    }

  // try to create an App Name key
  lRetCode = RegCreateKeyEx ( HKEY_CURRENT_USER,
                              "App Name",
                              0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE,
                              NULL, &hKey2,
                              &dwDisposition);

  // if we failed, note it, and leave
  if (lRetCode != ERROR_SUCCESS) {
    printf ("Error in creating App Name key\n");
    return (0) ;
    }

  // force the system to re-read the mapping into shared memory
  //    so that future invocations of the application will see it
  //    without the user having to reboot the system
  WritePrivateProfileStringW( NULL, NULL, NULL, L"appname.ini" );

  // if we get this far, all has gone well
  // let's write some added values
  WritePrivateProfileString ("Section1", "FirstKey",
                             "It all worked out okay.", "appname.ini");
  WritePrivateProfileString ("Section1", "SecondKey",
                             "By golly, it works.", "appname.ini");
  WritePrivateProfileSection ("Section1", "ThirdKey = Another Test.",
                              "appname.ini");

  // let's test our work
  GetPrivateProfileString ("Section1", "FirstKey",
                           "Bogus Value: Get didn't work", inBuf, 80,
                           "appname.ini");
  printf ("%s", inBuf);

  // okay, we are outta here
  return(0);

}

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetPrivateProfileString, WriteProfileString


WritePrivateProfileStruct

The WritePrivateProfileStruct function copies data into a key in the specified section of an initialization file. As it copies the data, the function calculates a checksum and appends it to the end of the data. The GetPrivateProfileStruct function uses the checksum to ensure the integrity of the data.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should store initialization information in the registry.

BOOL WritePrivateProfileStruct(
  LPCTSTR lpszSection,  // section name
  LPCTSTR lpszKey,      // key name
  LPVOID lpStruct,      // data buffer
  UINT uSizeStruct,     // size of data buffer
  LPCTSTR szFile        // initialization file
);

Parameters

lpszSection
[in] Pointer to a null-terminated string containing the name of the section to which the string will be copied. If the section does not exist, it is created. The name of the section is case independent, the string can be any combination of uppercase and lowercase letters.
lpszKey
[in] Pointer to the null-terminated string containing the name of the key to be associated with a string. If the key does not exist in the specified section, it is created. If this parameter is NULL, the entire section, including all keys and entries within the section, is deleted.
lpStruct
[in] Pointer to a buffer that contains the data to copy. If this parameter is NULL, the given key is deleted.
uSizeStruct
[in] Specifies the size, in bytes, of the buffer pointed to by the lpStruct parameter.
szFile
[in] Pointer to a null-terminated string that names the initialization file. If this parameter is NULL, the given information is copied into the Win.ini file.

Return Values

If the function successfully copies the string to the initialization file, the return value is nonzero.

If the function fails, or if it flushes the cached version of the most recently accessed initialization file, the return value is zero. To get extended error information, call GetLastError.

Remarks

Windows 95/98/Me: The system keeps a cached version of Win.ini to improve performance. If all three parameters are NULL, the function flushes the cache. The function always returns FALSE after flushing the cache, regardless of whether the flush succeeds or fails.

A section in the initialization file must have the following form:

[section]
key=string
      .
      .
      .

If the szFile parameter does not contain a full path and file name for the file, WritePrivateProfileString searches the Windows directory for the file. If the file does not exist, this function creates the file in the Windows directory.

If szFile contains a full path and file name and the file does not exist, WriteProfileString creates the file. The specified directory must already exist.

Windows NT/2000 or later: The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetPrivateProfileString, WriteProfileString


WriteProfileSection

The WriteProfileSection function replaces the contents of the specified section in the Win.ini file with specified keys and values.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should store initialization information in the registry.

BOOL WriteProfileSection(
  LPCTSTR lpAppName, // section name
  LPCTSTR lpString   // data buffer
);

Parameters

lpAppName
[in] Pointer to a null-terminated string containing the name of the section. This section name is typically the name of the calling application.
lpString
[in] Pointer to a buffer containing the new key names and associated values that are to be written to the named section.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

Windows 95/98/Me: If there is no section in Win.ini that matches the specified section name, WriteProfileSection creates the section at the end of the file and initializes the new section with the key name and value pairs specified in the lpString parameter.

Keys and values in the lpString buffer consist of one or more null-terminated strings, followed by a final null character. Each string has the following form:

key=string

The WriteProfileSection function is not case-sensitive; the strings can be a combination of uppercase and lowercase letters.

WriteProfileSection deletes the existing keys and values for the named section and inserts the key names and values in the buffer pointed to by lpString. The function does not attempt to correlate old and new key names; if the new names appear in a different order from the old names, any comments associated with preexisting keys and values in the initialization file will probably be associated with incorrect keys and values.

This operation is atomic; no other operations that read from or write to the initialization file are allowed while the information is being written.

Windows NT/2000 or later: The system maps most .ini file references to the registry, using the mapping defined under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the WriteProfileSection function writes information to the registry, not to the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetProfileSection, WritePrivateProfileSection


WriteProfileString

The WriteProfileString function copies a string into the specified section of the Win.ini file.

Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should store initialization information in the registry.

BOOL WriteProfileString(
  LPCTSTR lpAppName, // section name
  LPCTSTR lpKeyName, // key name
  LPCTSTR lpString   // string to write
);

Parameters

lpAppName
[in] Pointer to a null-terminated string that specifies the section to which the string is to be copied. If the section does not exist, it is created. The name of the section is not case-sensitive; the string can be any combination of uppercase and lowercase letters.
lpKeyName
[in] Pointer to a null-terminated string containing the key to be associated with the string. If the key does not exist in the specified section, it is created. If this parameter is NULL, the entire section, including all entries in the section, is deleted.
lpString
[in] Pointer to a null-terminated string to be written to the file. If this parameter is NULL, the key pointed to by the lpKeyName parameter is deleted.

Windows 95/98/Me: The system does not support the use of the TAB (\t) character as part of this parameter.

Return Values

If the function successfully copies the string to the Win.ini file, the return value is nonzero.

If the function fails, or if it flushes the cached version of Win.ini, the return value is zero. To get extended error information, call GetLastError.

Remarks

Windows 95/98/Me: The system keeps a cached version of Win.ini to improve performance. If all three parameters are NULL, the function flushes the cache. The function always returns FALSE after flushing the cache, regardless of whether the flush succeeds or fails.

A section in the Win.ini file must have the following form:

[section]
key=string
    .
    .
    .

Windows NT/2000 or later: The system maps most .ini file references to the registry, using the mapping defined under the following registry key:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

When the operation has been mapped, the WriteProfileString function writes information to the registry, not to the initialization file; the change in the storage location has no effect on the function's behavior.

The profile functions use the following steps to locate initialization information:

  1. Look in the registry for the name of the initialization file, say MyFile.ini, under IniFileMapping:

    HKEY_LOCAL_MACHINE\Software\Microsoft\
    Windows NT\CurrentVersion\IniFileMapping\myfile.ini

  2. Look for the section name specified by lpAppName. This will be a named value under myfile.ini, or a subkey of myfile.ini, or will not exist.
  3. If the section name specified by lpAppName is a named value under myfile.ini, then that value specifies where in the registry you will find the keys for the section.
  4. If the section name specified by lpAppName is a subkey of myfile.ini, then named values under that subkey specify where in the registry you will find the keys for the section. If the key you are looking for does not exist as a named value, then there will be an unnamed value (shown as <No Name>) that specifies the default location in the registry where you will find the key.
  5. If the section name specified by lpAppName does not exist as a named value or as a subkey under myfile.ini, then there will be an unnamed value (shown as <No Name>) under myfile.ini that specifies the default location in the registry where you will find the keys for the section.
  6. If there is no subkey for MyFile.ini, or if there is no entry for the section name, then look for the actual MyFile.ini on the disk and read its contents.

When looking at values in the registry that specify other registry locations, there are several prefixes that change the behavior of the .ini file mapping:

  • ! - this character forces all writes to go both to the registry and to the .ini file on disk.
  • # - this character causes the registry value to be set to the value in the Windows 3.1 .ini file when a new user logs in for the first time after setup.
  • @ - this character prevents any reads from going to the .ini file on disk if the requested data is not found in the registry.
  • USR: - this prefix stands for HKEY_CURRENT_USER, and the text after the prefix is relative to that key.
  • SYS: - this prefix stands for HKEY_LOCAL_MACHINE\SOFTWARE, and the text after the prefix is relative to that key.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

Registry Overview, Registry Functions, GetProfileString, WritePrivateProfileString


Registry Structures

The following structure is used with the registry.

VALENT


VALENT

The VALENT structure contains information about a registry value. The RegQueryMultipleValues function uses this structure.

typedef struct value_ent {
  LPTSTR     ve_valuename;
  DWORD      ve_valuelen;
  DWORD_PTR  ve_valueptr;
  DWORD      ve_type;
}VALENT, *PVALENT;

Members

ve_valuename
Pointer to a null-terminated string. Before calling RegQueryMultipleValues, set this member to point to the name of a value to retrieve.
ve_valuelen
Specifies the size, in bytes, of the data pointed to by ve_valueptr.
ve_valueptr
Pointer to the data for the value entry. This is a pointer to the value's data returned in the lpValueBuf buffer filled in by RegQueryMultipleValues.
ve_type
Specifies a code indicating the type of data pointed to by ve_valueptr. For a list of the possible type codes, see Registry Value Types.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.51 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winreg.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

Registry Overview, Registry Structures, RegQueryMultipleValues


Registry Value Types

A registry value can store data in various formats. When you store data under a registry value, for instance by calling the RegSetValueEx function, you can specify one of the following values to indicate the type of data being stored. When you retrieve a registry value, functions such as RegQueryValueEx use these values to indicate the type of data retrieved.

Value | Meaning
REG_BINARY | Binary data in any form.
REG_DWORD | A 32-bit number.
REG_DWORD_LITTLE_ENDIAN A 32-bit number in little-endian format. This is equivalent to REG_DWORD.

In little-endian format, a multi-byte value is stored in memory from the lowest byte (the "little end") to the highest byte. For example, the value 0x12345678 is stored as (0x78 0x56 0x34 0x12) in little-endian format.

Windows NT/Windows 2000, Windows 95, and Windows 98 are designed to run on little-endian computer architectures. A user may connect to computers that have big-endian architectures, such as some UNIX systems.

REG_DWORD_BIG_ENDIAN A 32-bit number in big-endian format.

In big-endian format, a multi-byte value is stored in memory from the highest byte (the "big end") to the lowest byte. For example, the value 0x12345678 is stored as (0x12 0x34 0x56 0x78) in big-endian format.
REG_EXPAND_SZ | A null-terminated string that contains unexpanded references to environment variables (for example, "%PATH%"). It will be a Unicode or ANSI string depending on whether you use the Unicode or ANSI functions. To expand the environment variable references, use the ExpandEnvironmentStrings function.
REG_LINK | A Unicode symbolic link. Used internally; applications should not use this type.
REG_MULTI_SZ | An array of null-terminated strings, terminated by two null characters.
REG_NONE | No defined value type.
REG_QWORD | A 64-bit number.
REG_QWORD_LITTLE_ENDIAN | A 64-bit number in little-endian format. This is equivalent to REG_QWORD.
REG_RESOURCE_LIST | A device-driver resource list.
REG_SZ | A null-terminated string. It will be a Unicode or ANSI string, depending on whether you use the Unicode or ANSI functions.


System Information

The system information functions and messages describe or change the system configuration, settings, and attributes.

  • About System Information
  • Using System Information
  • System Information Reference


About System Information

The functions described in this overview retrieve a variety of data. The system configuration information describes the computer hardware, computer name, and user name. The operating system configuration information describes the operating system version, key directories, and environment variables. The system parameters describe system attributes. The system metrics provide the dimensions of the elements in the display area.

The following sections describes how to obtain these types of information:

  • Hardware Configuration
  • Computer Names
  • Operating System Version
  • Operating System Configuration
  • System Parameters
  • System Metrics


Hardware Configuration

The hardware configuration functions retrieve information such as processor, hardware profile, and keyboard information.

The GetSystemInfo function retrieves processor and memory information, such as the page size, original equipment manufacturer (OEM) identifier, number and type of processors, application address range, and so on. The IsProcessorFeaturePresent function retrieves information about the floating-point operations and instruction sets supported by the processor.

The GetCurrentHwProfile function retrieves information about the hardware profile. The hardware profile includes information such as the docking state, globally unique identifier (GUID), and display name for the profile. The GetKeyboardType function retrieves such information as the type of keyboard and the number of function keys on the current keyboard.


Computer Names

DNS names consist of one or more components separated by a period (for example, msdn.microsoft.com). Each component can be up to 63 bytes of UTF-8 characters and must consist of valid characters. The name is not case sensitive. DNS names are represented in the UTF-8 character set or Unicode.

A computer is uniquely identified by its fully qualified DNS name, which consists of its DNS host name and the name of the DNS domain to which it is assigned. To retrieve a computer's fully qualified DNS name, DNS host name, or DNS domain name, call the GetComputerNameEx function. To set a computer's DNS host name or DNS domain name, call the SetComputerNameEx function. Name changes do not take effect until the user restarts the computer.

NetBIOS names consist of up to 15 bytes of OEM characters including letters, digits, hyphens, and periods. Some characters are specific to the character set. NetBIOS names are typically represented in the OEM character set. The OEM character set depends on the locale. Some OEM character sets represent certain characters as two bytes. NetBIOS names, by convention, are represented in uppercase where the translation algorithm from lowercase to uppercase is OEM character set dependent.

The SetComputerNameEx and GetComputerNameEx functions can also set and retrieve the computer's NetBIOS name. By convention, the NetBIOS name and the DNS host name are interdependent. When you modify the DNS name, the NetBIOS name is also updated. The NetBIOS name is the OEM representation of the DNS host name up to MAX_COMPUTERNAME_LENGTH characters. If you set a DNS host name of more than MAX_COMPUTERNAME_LENGTH characters, the NetBIOS name is set to a truncated version of the DNS host name. Otherwise, the whole DNS host name is translated into the OEM NetBIOS name. Warning: If you modify the NetBIOS name so that it is not a truncated mapping of the DNS name, you will break applications that use functions such as DnsHostnameToComputerName which rely on this convention.

Windows 95/98, Windows NT 4.0 and earlier: These systems do not provide support for DNS names. On these systems, you can use the GetComputerName function to retrieve the NetBIOS name and the SetComputerName function to set it. As with SetComputerNameEx, name changes by SetComputerName do not take effect until the user restarts the computer.


Operating System Version

The GetVersionEx function retrieves the major and minor version numbers and other information about the currently running version of the operating system. The VerifyVersionInfo function enables you to determine whether the current system satisfies a specified set of operating system version conditions. For more information, see the following topics:

  • Getting the System Version
  • Verifying the System Version

Identifying the current operating system is usually not the best way to determine whether a particular operating system feature is present. This is because the operating system may have had new features added in a redistributable DLL. Rather than using GetVersionEx to determine the operating system platform or version number, test for the presence of the feature itself.

To determine the best way to test for a feature, refer to the documentation for the feature of interest. The following list discusses some common techniques for feature detection:

  • You can test for the presence of the functions associated with a feature. To test for the presence of a function in a system DLL, call the LoadLibrary function to load the DLL. Then call the GetProcAddress function to determine whether the function of interest is present in the DLL. Use the pointer returned by GetProcAddress to call the function. Note that even if the function is present, it may be a stub that just returns an error code such as ERROR_CALL_NOT_IMPLEMENTED.
  • You can determine the presence of some features by using the GetSystemMetrics function. For example, you can detect multiple display monitors by calling GetSystemMetrics(SM_CMONITORS).
  • There are several versions of the redistributable DLLs that implement shell and common control features. For information about determining which versions are present on the system your application is running on, see the topic Shell Versions.


Operating System Configuration

The Windows directory is the directory that contains Windows-based applications, initialization files, and help files. The GetWindowsDirectory function retrieves the path to this directory. Applications that create files should do so in the Windows directory. This is the only directory guaranteed to be private to a user running a shared version of the operating system. The system directory is the directory that contains dynamic-link libraries, drivers, and font files. The GetSystemDirectory function retrieves the path to this directory.

The GetUserName function retrieves the name of the user currently logged onto the system. The user name is either the logon name or the user's full name, if the latter is included in the registry.

An environment variable is a symbolic variable that represents some element of the system, such as a path, a file name, or other literal data. For example, the environment variable PATH represents the directories in which to search for executable files. When a user logs on, the system initializes environment variables based on the environment section of the registry. The ExpandEnvironmentStrings function retrieves the values of specified environment variables.

Windows 2000 or later: Additional information is provided by the IADsADSystemInfo interface.


System Parameters

The SystemParametersInfo function retrieves or sets various system attributes, such as double-click time, screen saver time-out, window border width, and desktop pattern. When an application uses SystemParametersInfo to set a parameter, the change takes place immediately. This function also enables applications to update the user profile, so changes to the system will be preserved when the system is restarted.


System Metrics

Display elements are the parts of a window and the display that appear on the system display screen. System metrics are the dimensions of various display elements. Typical system metrics include the window border width, icon height, and so on. System metrics also describe other aspects of the system, such as whether a mouse is installed, double-byte characters are supported, or a debugging version of the operating system is installed. The GetSystemMetrics function retrieves the specified system metric.

Applications can also retrieve and set the color of window elements such as menus, scroll bars, and buttons by using the GetSysColor and SetSysColors functions, respectively.


Using System Information

  • Getting System Information
  • Getting the System Version
  • Getting Hardware Information
  • Changing the Colors of Window Elements


Getting System Information

The following example uses the GetComputerName, GetUserName, GetSystemDirectory, GetWindowsDirectory, and ExpandEnvironmentStrings functions to get information that describes the system configuration. This example displays the information in a window's client area.

LPTSTR lpszSystemInfo;     // pointer to system information string
DWORD cchBuff = 256;       // size of computer or user name
TCHAR tchBuffer2[BUFFER];  // buffer for concatenated string

DWORD dwResult;            // function return value

SYSTEM_INFO siSysInfo;     // structure for hardware information
int aTabs[1] = {260};      // tab stop for TabbedTextOut

TCHAR tchBuffer[BUFFER];   // buffer for expanded string
int nSize;                 // size of string

lpszSystemInfo = tchBuffer2;

// Get and display the name of the computer.

GetComputerName(lpszSystemInfo, &cchBuff);

nSize = sprintf(tchBuffer, "Computer name:  %s",
    lpszSystemInfo);
TextOut(hdc, 15, 20, tchBuffer, nSize);

// Get and display the user name.

GetUserName(lpszSystemInfo, &cchBuff);

nSize = sprintf(tchBuffer, "User name:  %s",
    lpszSystemInfo);
TextOut(hdc, 15, 40, tchBuffer, nSize);

// Get and display the system directory.

nSize = GetSystemDirectory(lpszSystemInfo, MAX_PATH);

nSize = sprintf(tchBuffer, "System directory:  %s",
    lpszSystemInfo);
TextOut(hdc, 15, 60, tchBuffer, nSize);

// Get and display the Windows directory.

nSize = GetWindowsDirectory(lpszSystemInfo, MAX_PATH);

nSize = sprintf(tchBuffer, "Windows directory:  %s",
    lpszSystemInfo);
TextOut(hdc, 15, 80, tchBuffer, nSize);

// Display the "environment variables" header.

nSize = sprintf(tchBuffer,
    "Environment variables (partial list):");
TextOut(hdc, 15, 105, tchBuffer, nSize);

// Expand the OS and NTVERSION environment variables.

dwResult = ExpandEnvironmentStrings(
               "OS=%OS%     NTVERSION=%NTVERSION%",
               lpszSystemInfo,
               BUFFER);

TextOut(hdc, 25, 120, (LPCTSTR) lpszSystemInfo,
    dwResult - 1);

// Expand the PATH environment variable.

dwResult = ExpandEnvironmentStrings(
               "PATH=%PATH%",
               lpszSystemInfo,
               BUFFER);

TextOut(hdc, 25, 135, (LPCTSTR) lpszSystemInfo,
    dwResult - 1);

// Expand the LIBPATH environment variable.

dwResult = ExpandEnvironmentStrings(
               "LIBPATH=%LIBPATH%",
               lpszSystemInfo,
               BUFFER);

TextOut(hdc, 25, 150, (LPCTSTR) lpszSystemInfo,
    dwResult - 1);

// Expand the TMP environment variable.

dwResult = ExpandEnvironmentStrings(
               "TMP=%TMP%",
               lpszSystemInfo,
               BUFFER);

TextOut(hdc, 25, 165, (LPCTSTR) lpszSystemInfo,
    dwResult - 1);


Getting the System Version

The following example uses the GetVersionEx function to retrieve version information about the currently running operating system.

Note If your application requires a particular operating system version, use the VerifyVersionInfo function to determine whether the currently running system satisfies your requirements. For sample code that uses VerifyVersionInfo, see Verifying the System Version.

#include <windows.h>
#include <stdio.h>

BOOL DisplaySystemVersion()
{
   OSVERSIONINFOEX osvi;
   BOOL bOsVersionInfoEx;

   // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
   //
   // If that fails, try using the OSVERSIONINFO structure.

   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

   if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
   {
      // If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO.

      osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
      if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) )
         return FALSE;
   }

   switch (osvi.dwPlatformId)
   {
      case VER_PLATFORM_WIN32_NT:

      // Test for the product.

         if ( osvi.dwMajorVersion <= 4 )
            printf("Microsoft Windows NT ");

         if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 )
            printf ("Microsoft Windows 2000 ");

         if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 )
            printf ("Whistler ");

      // Test for product type.

         if( bOsVersionInfoEx )
         {
            if ( osvi.wProductType == VER_NT_WORKSTATION )
            {
               if( osvi.wSuiteMask & VER_SUITE_PERSONAL )
                  printf ( "Personal " );
               else
                  printf ( "Professional " );
            }

            else if ( osvi.wProductType == VER_NT_SERVER )
            {
               if( osvi.wSuiteMask & VER_SUITE_DATACENTER )
                  printf ( "DataCenter Server " );
               else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE )
                  printf ( "Advanced Server " );
               else
                  printf ( "Server " );
            }
         }
         else
         {
            HKEY hKey;
            char szProductType[80];
            DWORD dwBufLen;

            RegOpenKeyEx( HKEY_LOCAL_MACHINE,
               "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
               0, KEY_QUERY_VALUE, &hKey );
            RegQueryValueEx( hKey, "ProductType", NULL, NULL,
               (LPBYTE) szProductType, &dwBufLen);
            RegCloseKey( hKey );
            if ( lstrcmpi( "WINNT", szProductType) == 0 )
               printf( "Workstation " );
            if ( lstrcmpi( "SERVERNT", szProductType) == 0 )
               printf( "Server " );
         }

      // Display version, service pack (if any), and build number.

         if ( osvi.dwMajorVersion <= 4 )
         {
            printf ("version %d.%d %s (Build %d)\n",
               osvi.dwMajorVersion,
               osvi.dwMinorVersion,
               osvi.szCSDVersion,
               osvi.dwBuildNumber & 0xFFFF);
         }
         else
         {
            printf ("%s (Build %d)\n",
               osvi.szCSDVersion,
               osvi.dwBuildNumber & 0xFFFF);
         }
         break;

      case VER_PLATFORM_WIN32_WINDOWS:

         if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
         {
             printf ("Microsoft Windows 95 ");
             if ( osvi.szCSDVersion[1] == 'C' )
                printf("OSR2 " );
         }

         if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
         {
             printf ("Microsoft Windows 98 ");
             if ( osvi.szCSDVersion[1] == 'A' )
                printf("SE " );
         }

         if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
         {
             printf ("Microsoft Windows Me ");
         }
         break;

      case VER_PLATFORM_WIN32s:

         printf ("Microsoft Win32s ");
         break;
   }
   return TRUE;
}


Verifying the System Version

This topic contains three examples. They determine whether the application is running on the following systems:

  • Windows 2000, Service Pack 1 or later
  • Windows 2000 Professional
  • Terminal Services is installed

The main steps in each example are as follows:

  • Set the appropriate values in the OSVERSIONINFOEX structure
  • Setting the appropriate condition mask using the VER_SET_CONDITION macro
  • Call the VerifyVersionInfo function to perform the test.

The following example determines whether the application is running on Windows 2000 Service Pack 1 or later.

BOOL Is_Win2000_SP1_or_Later ()
{
   OSVERSIONINFOEX osvi;
   DWORDLONG dwlConditionMask = 0;

   // Initialize the OSVERSIONINFOEX structure.

   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
   osvi.dwMajorVersion = 5;
   osvi.dwMinorVersion = 0;
   osvi.wServicePackMajor = 1;

   // Initialize the condition mask.

   VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION,
      VER_GREATER_EQUAL );
   VER_SET_CONDITION( dwlConditionMask, VER_MINORVERSION,
      VER_GREATER_EQUAL );
   VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMAJOR,
      VER_GREATER_EQUAL );

   // Perform the test.

   return VerifyVersionInfo(
      &osvi,
      VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR,
      dwlConditionMask);
}

Testing for other conditions involves a simple modification to this code. For example, the following code verifies that the application is running on Windows 2000 Professional.

BOOL Is_Win2000_Professional ()
{
   OSVERSIONINFOEX osvi;
   DWORDLONG dwlConditionMask = 0;

   // Initialize the OSVERSIONINFOEX structure.

   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
   osvi.dwMajorVersion = 5;
   osvi.wProductType = VER_NT_WORKSTATION;

   // Initialize the condition mask.

   VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION,
      VER_GREATER_EQUAL );
   VER_SET_CONDITION( dwlConditionMask, VER_PRODUCT_TYPE,
      VER_EQUAL );

   // Perform the test.

   return VerifyVersionInfo(
      &osvi,
      VER_MAJORVERSION | VER_PRODUCT_TYPE,
      dwlConditionMask);
}

Finally, the following example tests whether Terminal Services is installed.

BOOL Is_Terminal_Services ()
{
   OSVERSIONINFOEX osvi;
   DWORDLONG dwlConditionMask = 0;

   // Initialize the OSVERSIONINFOEX structure.

   ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
   osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
   osvi.wSuiteMask = VER_SUITE_TERMINAL;

   // Initialize the condition mask.

   VER_SET_CONDITION( dwlConditionMask, VER_SUITENAME,
      VER_AND );

   // Perform the test.

   return VerifyVersionInfo(
      &osvi,
      VER_SUITENAME,
      dwlConditionMask);
}


Detecting a Product Suite

The following example uses the VerifyVersionInfo function to determine whether the Microsoft BackOffice® and Terminal Services product suites are installed on the local computer. This example uses the VER_AND flag, which causes the function to return TRUE only if both product suites are present. If you specify the VER_OR flag, VersionVerifyInfo returns TRUE if either suite is present.

You can use similar code to detect other product suites such as Microsoft® Small Business Server or Windows 2000 Advanced Server.

BOOL CheckProductSuites () {
  OSVERSIONINFOEX osvi;
  DWORDLONG dwlConditionMask = 0;

  // Initialize the OSVERSIONINFOEX structure.

  ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  osvi.wSuiteMask = VER_SUITE_BACKOFFICE | VER_SUITE_TERMINAL;

  // Set up the condition mask.

  VER_SET_CONDITION( dwlConditionMask,
          VER_SUITENAME, VER_AND );

  // Perform the test.

  return VerifyVersionInfo(
          &osvi,
          VER_SUITENAME,
          dwlConditionMask);
}


Getting Hardware Information

The following example uses the GetSystemInfo function to obtain hardware information such as the OEM identifier, processor type, page size, and so on. The example displays the information in a window's client area.

SYSTEM_INFO siSysInfo;   // struct. for hardware information
int aTabs[1] = {260};    // tab stop for TabbedTextOut

TCHAR tchBuffer[BUFFER]; // buffer for expanded string
int nSize;               // size of string

// Display the "hardware information" header.

nSize = sprintf(tchBuffer,
    "Hardware information:");
TextOut(hdc, 15, 20, tchBuffer, nSize);

// Copy the hardware information to the SYSTEM_INFO structure.

GetSystemInfo(&siSysInfo);

// Display the contents of the SYSTEM_INFO structure.

nSize = sprintf(tchBuffer,
    "OEM ID: %u\tNumber of Processors: %u",
    siSysInfo.dwOemId,
    siSysInfo.dwNumberOfProcessors);
TabbedTextOut(hdc, 25, 40, tchBuffer,
    nSize, 1, aTabs, 25);

nSize = sprintf(tchBuffer,
    "Page size: %u\tProcessor Type: %u",
    siSysInfo.dwPageSize,
    siSysInfo.dwProcessorType);
TabbedTextOut(hdc, 25, 60, tchBuffer,
    nSize, 1, aTabs, 25);

nSize = sprintf(tchBuffer,
    "Minimum app address: %lx\tMaximum app address: %lx",
    siSysInfo.lpMinimumApplicationAddress,
    siSysInfo.lpMaximumApplicationAddress);
TabbedTextOut(hdc, 25, 80, tchBuffer,
    nSize, 1, aTabs, 25);

nSize = sprintf(tchBuffer,
    "Active processor mask: %u",
    siSysInfo.dwActiveProcessorMask);
TextOut(hdc, 25, 100, tchBuffer, nSize);

The following example uses the GetSystemMetrics function to determine whether a mouse is installed and whether the mouse buttons are swapped. The example also uses the SystemParametersInfo function to retrieve the mouse threshold and speed. It displays the information in a message box.

TCHAR tchBuffer[BUFFER]; // buffer for expanded string
int nSize;               // size of string

BOOL fResult;            // system shutdown flag

int aMouseInfo[3];       // array for mouse information

// Is there a mouse?

fResult = GetSystemMetrics(SM_MOUSEPRESENT);

if (fResult == 0)
{
    // Indicate if there is no mouse.

    nSize = sprintf(tchBuffer, "No mouse installed.");
}
else
{
    // If there is a mouse, determine whether its buttons are swapped.

    fResult = GetSystemMetrics(SM_SWAPBUTTON);

    if (fResult == 0)
    {
        nSize = sprintf(tchBuffer, "Buttons not swapped.\r");
    }
    else
    {
        nSize = sprintf(tchBuffer, "Buttons swapped.\r");
    }

    // Get the mouse speed and the threshold values.

    SystemParametersInfo(SPI_GETMOUSE, // get mouse information
        NULL,                          // not used
        &aMouseInfo,                   // holds mouse information
        NULL);                         // not used

    nSize += sprintf(tchBuffer + nSize,
        "Speed: %d\r", aMouseInfo[2]);
    sprintf(tchBuffer + nSize,
        "Threshold (x,y): %d,%d",
        aMouseInfo[0], aMouseInfo[1]);
}

// Display the mouse information.

MessageBox(NULL, tchBuffer, "Mouse information",
    MB_ICONINFORMATION);

This next example uses SystemParametersInfo to double the mouse speed and update the MouseSpeed value in the WIN.INI file.

TCHAR tchBuffer[BUFFER]; // buffer for expanded string
int nSize;               // size of string

int aMouseInfo[3];       // array for mouse information

// Get the current mouse speed.

SystemParametersInfo(SPI_GETMOUSE, // get mouse information
    NULL,                          // not used
    &aMouseInfo,                   // holds mouse information
    NULL);                         // not used

// Double it.

aMouseInfo[2] = 2 * aMouseInfo[2];

// Change the mouse speed to the new value and update WIN.INI.

SystemParametersInfo(SPI_SETMOUSE, // set mouse information
    NULL,                          // not used
    aMouseInfo,                    // mouse information
    SPIF_UPDATEINIFILE);           // update win.ini


Changing the Colors of Window Elements

The following example uses the SetSysColors function to change the color of active window borders to dark purple, of active title bars to dark cyan, and of the window background to light gray.

// window elements to change
int aiElements[3] = {COLOR_ACTIVEBORDER,
                     COLOR_ACTIVECAPTION,
                     COLOR_WINDOW};

// array of RGB values
DWORD aColors[3];

// Define the new colors.

aColors[0] = RGB(0x80, 0x00, 0x80);  // dark purple
aColors[1] = RGB(0x00, 0x80, 0x80);  // dark cyan
aColors[2] = RGB(0xC0, 0xC0, 0xC0);  // light gray

// Set the window elements in aiElements to the colors
// specified in aColors.

SetSysColors(3, aiElements, aColors);

The next example uses the GetSysColor function to retrieve the color of the window background and displays the red, green, blue (RGB) value, in hexadecimal notation, in a message box.

DWORD dwResult;           // function return value

TCHAR tchBuffer[BUFFER];  // buffer for expanded string
int nSize;                // size of string

// Get the color of the window background.

dwResult = GetSysColor(COLOR_WINDOW);

nSize = sprintf(tchBuffer,
    "Window color: {%x, %x, %x}",
    GetRValue(dwResult),
    GetGValue(dwResult),
    GetBValue(dwResult));

MessageBox(NULL, tchBuffer, "GetSysColor", MB_ICONINFORMATION);


System Information Reference

The following elements are used with system information.

  • System Information Functions
  • System Information Structures
  • System Information Messages
  • System Information Macros
  • System Information Enumeration Types


System Information Functions

The following functions are used to retrieve or set system information.

Function | Description
DnsHostnameToComputerName | Converts a DNS name to a NetBIOS name.
ExpandEnvironmentStrings | Replaces environment-variable strings with their defined values.
GetComputerName | Retrieves the NetBIOS name of the local computer.
GetComputerNameEx | Retrieves the NetBIOS or DNS name of the local computer.
GetComputerObjectName | Retrieves the local computer's name in a specified format.
GetCurrentHwProfile | Retrieves the current hardware profile for the local computer.
GetKeyboardType | Retrieves information about the current keyboard.
GetSysColor | Retrieves the current color of a display element.
GetSystemDirectory | Retrieves the path of the system directory.
GetSystemInfo | Retrieves information about the current system.
GetSystemMetrics | Retrieves system metrics and configuration settings.
GetSystemWindowsDirectory | Retrieves the path of the shared Windows directory on a multiuser system.
GetSystemWow64Directory | Retrieves the path of the system directory used by WOW64.
GetUserName | Retrieves the user name of the current thread.
GetUserNameEx | Retrieves the name of the user or other security principal associated with the calling thread. You can specify the format of the returned name.
GetVersion | Retrieves the version number of the operating system.
GetVersionEx | Retrieves the version of the current operating system.
GetWindowsDirectory | Retrieves the path of the Windows directory.
IsProcessorFeaturePresent | Determines whether a processor feature is supported by the current computer.
SetComputerName | Stores a new NetBIOS name for the local computer.
SetComputerNameEx | Stores a new NetBIOS or DNS name for the local computer.
SetSysColors | Sets the colors for one or more display elements.
SystemParametersInfo | Queries or sets system-wide parameters.
TranslateName | Converts a directory service object name from one format to another.
VerifyVersionInfo | Compares a set of version requirements to the values for the current operating system.
VerSetConditionMask | Builds the condition mask for the VerifyVersionInfo function.


DnsHostnameToComputerName

The DnsHostnameToComputerName function converts a DNS-style host name to a NetBIOS-style computer name.

BOOL DnsHostnameToComputerName(
  LPCTSTR Hostname,      // DNS name
  LPTSTR ComputerName,  // name buffer
  LPDWORD nSize         // size of name buffer
);

Parameters

Hostname
[in] Pointer to a string that specifies the DNS name. If the DNS name is not a valid, translatable name, the function fails.
ComputerName
[out] Pointer to a string buffer that receives the computer name. The buffer size should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters.
nSize
[in/out] On input, specifies the size, in TCHARs, of the buffer. On output, receives the number of TCHARs copied to the destination buffer, not including the terminating null character.

If the buffer is too small, the function fails, GetLastError returns ERROR_BUFFER_OVERFLOW, and nSize receives the required buffer size, including the terminating null character.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Remarks

This function performs a textual mapping of the name. This convention limits the names of computers to be the common subset of the names. (Specifically, the leftmost label of the DNS name is truncated to 15-bytes of OEM characters.) Therefore, do not use this function to convert a DNS domain name to a NetBIOS domain name. There is no textual mapping for domain names.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

System Information Overview, System Information Functions, GetComputerNameEx, SetComputerNameEx


ExpandEnvironmentStrings

The ExpandEnvironmentStrings function expands environment-variable strings and replaces them with their defined values.

DWORD ExpandEnvironmentStrings(
  LPCTSTR lpSrc, // string with environment variables
  LPTSTR lpDst,  // string with expanded strings
  DWORD nSize    // maximum characters in expanded string
);

Parameters

lpSrc
[in] Pointer to a null-terminated string that contains environment-variable strings of the form: %variableName%. For each such reference, the %variableName% portion is replaced with the current value of that environment variable.

The replacement rules are the same as those used by the command interpreter. Case is ignored when looking up the environment-variable name. If the name is not found, the %variableName% portion is left undisturbed.

lpDst
[out] Pointer to a buffer to receive a copy of the source buffer after all environment-variable name substitutions have been performed.
nSize
[in] Specifies the maximum number of TCHARs that can be stored in the buffer pointed to by the lpDst parameter, including the terminating null character.

Return Values

If the function succeeds, the return value is the number of TCHARs stored in the destination buffer, including the terminating null character. If the destination buffer is too small to hold the expanded string, the return value is the required buffer size, in TCHARs.

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

Remarks

There are certain restrictions on the size of the lpSrc and lpDst buffers.

  • On Windows NT 4.0 and earlier, these buffers are limited to 32K.
  • On Windows 2000, these buffers are limited to 32K in the ANSI version, but there is no size restriction in the Unicode version.
  • On Windows 95/98, the ANSI version has no size restriction; the Unicode version is not supported.

For an example, see Getting System Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions


GetComputerName

The GetComputerName function retrieves the NetBIOS name of the local computer. This name is established at system startup, when the system reads it from the registry.

If the local computer is a node in a cluster, GetComputerName returns the name of the node.

Windows 2000 or later: GetComputerName retrieves only the NetBIOS name of the local computer. To retrieve the DNS host name, DNS domain name, or the fully qualified DNS name, call the GetComputerNameEx function.

Windows 2000 or later: Additional information is provided by the IADsADSystemInfo interface.

BOOL GetComputerName(
  LPTSTR lpBuffer,  // computer name
  LPDWORD lpnSize   // size of name buffer
);

Parameters

lpBuffer
[out] Pointer to a buffer that receives a null-terminated string containing the computer name. The buffer size should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters.
lpnSize
[in/out] On input, specifies the size, in TCHARs, of the buffer. On output, receives the number of TCHARs copied to the destination buffer, not including the terminating null character.

If the buffer is too small, the function fails and GetLastError returns ERROR_BUFFER_OVERFLOW.

Windows 95/98/Me: GetComputerName fails if the input size is less than MAX_COMPUTERNAME_LENGTH + 1.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Remarks

The GetComputerName function retrieves the NetBIOS name established at system startup. Name changes made by the SetComputerName or SetComputerNameEx functions do not take effect until the user restarts the computer.

For an example, see Getting System Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, GetComputerNameEx, SetComputerName, SetComputerNameEx


GetComputerNameEx

The GetComputerNameEx function retrieves a NetBIOS or DNS name associated with the local computer. The names are established at system startup, when the system reads them from the registry.

GetComputerNameEx can retrieve the NetBIOS name retrieved by the GetComputerName function. In addition, GetComputerNameEx can retrieve fully qualified, host, and domain DNS names.

If the local computer is a node in a cluster, GetComputerNameEx can return either the name of the cluster or the name of the local computer.

BOOL GetComputerNameEx(
  COMPUTER_NAME_FORMAT NameType,  // name type
  LPTSTR lpBuffer,                // name buffer
  LPDWORD lpnSize                 // size of name buffer
);

Parameters

NameType
[in] A value from the COMPUTER_NAME_FORMAT enumeration type that specifies the type of name to retrieve.

This parameter can be one of the following values from the COMPUTER_NAME_FORMAT enumeration type that specifies the type of name to retrieve.
Value | Description
ComputerNameNetBIOS | The NetBIOS name of the local computer. If the local computer is a node in a cluster, lpBuffer receives the NetBIOS name of the cluster.
ComputerNameDnsHostname | The DNS host name of the local computer. If the local computer is a node in a cluster, lpBuffer receives the DNS host name of the cluster.
ComputerNameDnsDomain | The name of the DNS domain assigned to the local computer. If the local computer is a node in a cluster, lpBuffer receives the DNS domain name of the cluster.
ComputerNameDnsFullyQualified | The fully qualified DNS name that uniquely identifies the local computer. This name is a combination of the DNS host name and the DNS domain name, using the form HostName.DomainName. If the local computer is a node in a cluster, lpBuffer receives the fully qualified DNS name of the cluster.
ComputerNamePhysicalNetBIOS | The NetBIOS name of the local computer. If the local computer is a node in a cluster, lpBuffer receives the NetBIOS name of the local computer, not the name of the cluster.
ComputerNamePhysicalDnsHostname | The DNS host name of the local computer. If the local computer is a node in a cluster, lpBuffer receives the DNS host name of the local computer, not the name of the cluster.
ComputerNamePhysicalDnsDomain | The name of the DNS domain assigned to the local computer. If the local computer is a node in a cluster, lpBuffer receives the DNS domain name of the local computer, not the name of the cluster.
ComputerNamePhysicalDnsFullyQualified The fully qualified DNS name that uniquely identifies the computer. If the local computer is a node in a cluster, lpBuffer receives the fully qualified DNS name of the local computer, not the name of the cluster.

The fully qualified DNS name is a combination of the DNS host name and the DNS domain name, using the form HostName.DomainName.

lpBuffer
[out] Pointer to a buffer that receives a null-terminated string containing the computer name.

The length of the name may be greater than MAX_COMPUTERNAME_LENGTH characters because DNS allows longer names.

lpnSize
[in/out] On input, specifies the size, in TCHARs, of the buffer. On output, receives the number of TCHARs copied to the destination buffer, including the terminating null character.

If the buffer is too small, the function fails and GetLastError returns ERROR_MORE_DATA.

Return Value

If the function succeeds, the return value is a nonzero value.

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

Remarks

The GetComputerNameEx function retrieves the NetBIOS or DNS names established at system startup. Name changes made by the SetComputerName or SetComputerNameEx functions do not take effect until the user restarts the computer.

When a computer is a node in a cluster, an application can get a cluster name instead of the node name by using the appropriate value for NameType. This lets a cluster-unaware application see a consistent node name regardless of which cluster node is hosting the application. For this to happen, the following must be true:

  • the application is running as a cluster resource with a dependency on a cluster Network Name [sic] resource.
  • the resource DLL managing the application calls ResUtilGetEnvironmentWithNetName and passes the resulting environment block to CreateProcess when starting the application. If your resource DLL manages a service, use ResUtilSetResourceServiceStartParameters and ResUtilSetResourceServiceEnvironment before bringing the service online.

If these are both true, GetComputerNameEx returns the specified cluster name from the environment space based on NameType. If these are not true, GetComputerNameEx returns the name of the local computer. For more information about clustering, see Windows Clustering.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

System Information Overview, System Information Functions, COMPUTER_NAME_FORMAT, GetComputerName, ResUtilGetEnvironmentWithNetName, ResUtilSetResourceServiceStartParameters, ResUtilSetResourceServiceEnvironment, SetComputerName, SetComputerNameEx


GetComputerObjectName

The GetComputerObjectName function retrieves the local computer's name in a specified format.

BOOLEAN GetComputerObjectName (
  EXTENDED_NAME_FORMAT NameFormat, // name format
  LPTSTR lpNameBuffer,             // name buffer
  PULONG nSize                     // size of name buffer
);

Parameters

NameFormat
[in] A value from the EXTENDED_NAME_FORMAT enumeration type indicating the desired name format. This value cannot be NameUnknown.
lpNameBuffer
[out] Pointer to a buffer that receives the name in the specified format.
nSize
[in/out] On input, specifies the size, in TCHARs, of the lpNameBuffer buffer. On output, receives the number of TCHARs copied to the destination buffer, including the terminating null character.

If the lpNameBuffer buffer is too small to hold the name, the function fails and nSize receives the required buffer size.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Secext.h; include Security.h.
Library: Use Secur32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

System Information Overview, System Information Functions, EXTENDED_NAME_FORMAT, GetComputerNameEx


GetCurrentHwProfile

The GetCurrentHwProfile function retrieves information about the current hardware profile for the local computer.

BOOL GetCurrentHwProfile(
  LPHW_PROFILE_INFO lpHwProfileInfo  // profile information
);

Parameters

lpHwProfileInfo
[out] Pointer to an HW_PROFILE_INFO structure that receives information about the current hardware profile.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Remarks

The GetCurrentHwProfile function retrieves the display name and globally unique identifier (GUID) string for the hardware profile. The function also retrieves the reported docking state for portable computers with docking stations.

The system generates a GUID for each hardware profile and stores it as a string in the registry. You can use GetCurrentHwProfile to retrieve the GUID string to use as a registry subkey under your application's configuration settings key in HKEY_CURRENT_USER. This enables you to store each user's settings for each hardware profile. For example, the Colors control panel application could use the subkey to store each user's color preferences for different hardware profiles, such as profiles for the docked and undocked states. Applications that use this functionality can check the current hardware profile when they start up, and update their settings accordingly.

Applications can also update their settings when a system device message, such as DBT_CONFIGCHANGED, indicates that the hardware profile has changed.

Example

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void main(void)
{
   HW_PROFILE_INFO   HwProfInfo;
   if (!GetCurrentHwProfile(&HwProfInfo))
   {
      _tprintf(TEXT("GetCurrentHwProfile failed with error %lx\n"),
                 GetLastError());
      return;
   }
   _tprintf(TEXT("DockInfo = %d\n"), HwProfInfo.dwDockInfo);
   _tprintf(TEXT("Profile Guid = %s\n"), HwProfInfo.szHwProfileGuid);
   _tprintf(TEXT("Friendly Name = %s\n"), HwProfInfo.szHwProfileName);
}

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 OSR2 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, DBT_CONFIGCHANGED, HW_PROFILE_INFO


GetKeyboardType

The GetKeyboardType function retrieves information about the current keyboard.

int GetKeyboardType(
  int nTypeFlag  // information type
);

Parameters

nTypeFlag
[in] Specifies the type of keyboard information to be retrieved. This parameter can be one of the following values.
Value | Meaning
0 | Keyboard type
1 | Keyboard subtype
2 | Number of function keys on the keyboard

Return Values

If the function succeeds, the return value specifies the requested information.

If the function fails and nTypeFlag is not one, the return value is zero; zero is a valid return value when nTypeFlag is one (keyboard subtype). To get extended error information, call GetLastError.

Remarks

The type may be one of the following values.

Value | Meaning
1 | IBM PC/XT or compatible (83-key) keyboard
2 | Olivetti "ICO" (102-key) keyboard
3 | IBM PC/AT (84-key) or similar keyboard
4 | IBM enhanced (101- or 102-key) keyboard
5 | Nokia 1050 and similar keyboards
6 | Nokia 9140 and similar keyboards
7 | Japanese keyboard

The subtype is an original equipment manufacturer (OEM)-dependent value.

The application can also determine the number of function keys on a keyboard from the keyboard type. Following are the number of function keys for each keyboard type.

Type | Number of function keys
1 | 10
2 | 12 (sometimes 18)
3 | 10
4 | 12
5 | 10
6 | 24
7 | Hardware dependent and specified by the OEM

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

System Information Overview, System Information Functions


GetSysColor

The GetSysColor function retrieves the current color of the specified display element. Display elements are the parts of a window and the display that appear on the system display screen.

DWORD GetSysColor(
  int nIndex   // display element
);

Parameters

nIndex
[in] Specifies the display element whose color is to be retrieved. This parameter can be one of the following values.
Value | Meaning
COLOR_3DDKSHADOW | Dark shadow for three-dimensional display elements.
COLOR_3DFACE, COLOR_BTNFACE | Face color for three-dimensional display elements and for dialog box backgrounds.
COLOR_3DHILIGHT, COLOR_3DHIGHLIGHT, COLOR_BTNHILIGHT, COLOR_BTNHIGHLIGHT | Highlight color for three-dimensional display elements (for edges facing the light source.)
COLOR_3DLIGHT | Light color for three-dimensional display elements (for edges facing the light source.)
COLOR_3DSHADOW, COLOR_BTNSHADOW | Shadow color for three-dimensional display elements (for edges facing away from the light source).
COLOR_ACTIVEBORDER | Active window border.
COLOR_ACTIVECAPTION Active window title bar.

Windows 98/Me, Windows 2000 or later: Specifies the left side color in the color gradient of an active window's title bar if the gradient effect is enabled.
COLOR_APPWORKSPACE | Background color of multiple document interface (MDI) applications.
COLOR_BACKGROUND, COLOR_DESKTOP | Desktop.
COLOR_BTNTEXT | Text on push buttons.
COLOR_CAPTIONTEXT | Text in caption, size box, and scroll bar arrow box.
COLOR_GRADIENTACTIVECAPTION | Windows 98/Me, Windows 2000 or later: Right side color in the color gradient of an active window's title bar. COLOR_ACTIVECAPTION specifies the left side color. Use SPI_GETGRADIENTCAPTIONS with the SystemParametersInfo function to determine whether the gradient effect is enabled.
COLOR_GRADIENTINACTIVECAPTION | Windows 98/Me, Windows 2000 or later: Right side color in the color gradient of an inactive window's title bar. COLOR_INACTIVECAPTION specifies the left side color.
COLOR_GRAYTEXT | Grayed (disabled) text. This color is set to 0 if the current display driver does not support a solid gray color.
COLOR_HIGHLIGHT | Item(s) selected in a control.
COLOR_HIGHLIGHTTEXT | Text of item(s) selected in a control.
COLOR_HOTLIGHT | Windows 98/Me, Windows 2000 or later: Color for a hot-tracked item. Single clicking a hot-tracked item executes the item.
COLOR_INACTIVEBORDER | Inactive window border.
COLOR_INACTIVECAPTION Inactive window caption.

Windows 98/Me, Windows 2000 or later: Specifies the left side color in the color gradient of an inactive window's title bar if the gradient effect is enabled.
COLOR_INACTIVECAPTIONTEXT | Color of text in an inactive caption.
COLOR_INFOBK | Background color for tooltip controls.
COLOR_INFOTEXT | Text color for tooltip controls.
COLOR_MENU | Menu background.
COLOR_MENUHILIGHT | Whistler: The color used to highlight menu items when the menu appears as a flat menu (see SystemParametersInfo). The highlighted menu item is outlined with COLOR_HIGHLIGHT.
COLOR_MENUBAR | Whistler: The background color for the menu bar when menus appear as flat menus (see SystemParametersInfo). However, COLOR_MENU continues to specify the background color of the menu popup.
COLOR_MENUTEXT | Text in menus.
COLOR_SCROLLBAR | Scroll bar gray area.
COLOR_WINDOW | Window background.
COLOR_WINDOWFRAME | Window frame.
COLOR_WINDOWTEXT | Text in windows.

Return Values

The function returns the red, green, blue (RGB) color value of the given element.

If the nIndex parameter is out of range, the return value is zero. Because zero is also a valid RGB value, you cannot use GetSysColor to determine whether a system color is supported by the current platform. Instead, use the GetSysColorBrush function, which returns NULL if the color is not supported.

Remarks

System colors for monochrome displays are usually interpreted as shades of gray.

To paint with a system color brush, an application should use GetSysColorBrush(nIndex) instead of CreateSolidBrush(GetSysColor(nIndex)), because GetSysColorBrush returns a cached brush (instead of allocating a new one).

For an example, see Changing the Colors of Window Elements.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

System Information Overview, System Information Functions, CreateSolidBrush, GetSysColorBrush, SetSysColors, SystemParametersInfo


GetSystemDirectory

The GetSystemDirectory function retrieves the path of the system directory. The system directory contains such files as dynamic-link libraries, drivers, and font files.

UINT GetSystemDirectory(
  LPTSTR lpBuffer,  // buffer for system directory
  UINT uSize        // size of directory buffer
);

Parameters

lpBuffer
[out] Pointer to the buffer to receive the null-terminated string containing the path. This path does not end with a backslash unless the system directory is the root directory. For example, if the system directory is named WINDOWS\SYSTEM on drive C, the path of the system directory retrieved by this function is C:\WINDOWS\SYSTEM.
uSize
[in] Specifies the maximum size of the buffer, in TCHARs. This value should be set to at least MAX_PATH.

Return Values

If the function succeeds, the return value is the length, in TCHARs, of the string copied to the buffer, not including the terminating null character. If the length is greater than the size of the buffer, the return value is the size of the buffer required to hold the path.

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

Remarks

Applications should not create files in the system directory. If the user is running a shared version of the operating system, the application does not have write access to the system directory. Applications should create files only in the directory returned by the GetWindowsDirectory function.

For an example, see Getting System Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, GetCurrentDirectory, GetWindowsDirectory, SetCurrentDirectory


GetSystemInfo

The GetSystemInfo function returns information about the current system.

VOID GetSystemInfo(
  LPSYSTEM_INFO lpSystemInfo  // system information
);

Parameters

lpSystemInfo
[out] Pointer to a SYSTEM_INFO structure that receives the information.

Return Values

This function does not return a value.

For an example, see Getting Hardware Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

System Information Overview, System Information Functions, SYSTEM_INFO


GetSystemMetrics

The GetSystemMetrics function retrieves various system metrics (widths and heights of display elements) and system configuration settings. All dimensions retrieved by GetSystemMetrics are in pixels.

int GetSystemMetrics(
  int nIndex   // system metric or configuration setting
);

Parameters

nIndex
[in] Specifies the system metric or configuration setting to retrieve. All SM_CX* values are widths. All SM_CY* values are heights. The following values are defined.
Value | Meaning
SM_ARRANGE | Flags specifying how the system arranged minimized windows. For more information about minimized windows, see the following Remarks section.
SM_CLEANBOOT Value that specifies how the system was started:

0 Normal boot
1 Fail-safe boot
2 Fail-safe with network boot

Fail-safe boot (also called SafeBoot) bypasses the user's startup files.
SM_CMONITORS | Windows 98/Me, Windows 2000 or later: Number of display monitors on the desktop. See Remarks for more information.
SM_CMOUSEBUTTONS | Number of buttons on mouse, or zero if no mouse is installed.
SM_CXBORDER,
SM_CYBORDER 		Width and height, in pixels, of a window border. This is equivalent to the SM_CXEDGE value for windows with the 3-D look.
SM_CXCURSOR,
SM_CYCURSOR 		Width and height, in pixels, of a cursor. The system cannot create cursors of other sizes.
SM_CXDLGFRAME,
SM_CYDLGFRAME 		Same as SM_CXFIXEDFRAME and SM_CYFIXEDFRAME.
SM_CXDOUBLECLK,
SM_CYDOUBLECLK 		Width and height, in pixels, of the rectangle around the location of a first click in a double-click sequence. The second click must occur within this rectangle for the system to consider the two clicks a double-click. (The two clicks must also occur within a specified time.)

To set the width and height of the double-click rectangle, call SystemParametersInfo with the SPI_SETDOUBLECLKHEIGHT and SPI_SETDOUBLECLKWIDTH flags.
SM_CXDRAG,
SM_CYDRAG 		Width and height, in pixels, of a rectangle centered on a drag point to allow for limited movement of the mouse pointer before a drag operation begins. This allows the user to click and release the mouse button easily without unintentionally starting a drag operation.
SM_CXEDGE,
SM_CYEDGE 		Dimensions, in pixels, of a 3-D border. These are the 3-D counterparts of SM_CXBORDER and SM_CYBORDER.
SM_CXFIXEDFRAME,
SM_CYFIXEDFRAME 		Thickness, in pixels, of the frame around the perimeter of a window that has a caption but is not sizable. SM_CXFIXEDFRAME is the heightof the horizontal border and SM_CYFIXEDFRAME is the width of the vertical border.

Same as SM_CXDLGFRAME and SM_CYDLGFRAME.
SM_CXFOCUSBORDER,
SM_CYFOCUSBORDER 		Whistler: The width of the left and right edges and the height of the top and bottom edges of the focus rectangle drawn by DrawFocusRect. These values are in pixels.
SM_CXFRAME,
SM_CYFRAME 		Same as SM_CXSIZEFRAME and SM_CYSIZEFRAME.
SM_CXFULLSCREEN,
SM_CYFULLSCREEN 		Width and height of the client area for a full-screen window on the primary display monitor. To get the coordinates of the portion of the screen not obscured by the system taskbar or by application desktop toolbars, call the SystemParametersInfo function with the SPI_GETWORKAREA value.
SM_CXHSCROLL,
SM_CYHSCROLL 		Width, in pixels, of the arrow bitmap on a horizontal scroll bar; and height, in pixels, of a horizontal scroll bar.
SM_CXHTHUMB | Width, in pixels, of the thumb box in a horizontal scroll bar.
SM_CXICON,
SM_CYICON 		The default width and height, in pixels, of an icon. The LoadIcon function can load only icons of these dimensions.
SM_CXICONSPACING,
SM_CYICONSPACING 		Dimensions, in pixels, of a grid cell for items in large icon view. Each item fits into a rectangle of this size when arranged. These values are always greater than or equal to SM_CXICON and SM_CYICON.
SM_CXMAXIMIZED,
SM_CYMAXIMIZED 		Default dimensions, in pixels, of a maximized top-level window on the primary display monitor.
SM_CXMAXTRACK,
SM_CYMAXTRACK 		Default maximum dimensions, in pixels, of a window that has a caption and sizing borders. This metric refers to the entire desktop. The user cannot drag the window frame to a size larger than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message.
SM_CXMENUCHECK,
SM_CYMENUCHECK 		Dimensions, in pixels, of the default menu check-mark bitmap.
SM_CXMENUSIZE,
SM_CYMENUSIZE 		Dimensions, in pixels, of menu bar buttons, such as the child window close button used in the multiple document interface.
SM_CXMIN,
SM_CYMIN 		Minimum width and height, in pixels, of a window.
SM_CXMINIMIZED,
SM_CYMINIMIZED 		Dimensions, in pixels, of a normal minimized window.
SM_CXMINSPACING
SM_CYMINSPACING 		Dimensions, in pixels, of a grid cell for minimized windows. Each minimized window fits into a rectangle this size when arranged. These values are always greater than or equal to SM_CXMINIMIZED and SM_CYMINIMIZED.
SM_CXMINTRACK,
SM_CYMINTRACK 		Minimum tracking width and height, in pixels, of a window. The user cannot drag the window frame to a size smaller than these dimensions. A window can override these values by processing the WM_GETMINMAXINFO message.
SM_CXSCREEN,
SM_CYSCREEN 		Width and height, in pixels, of the screen of the primary display monitor. These are the same values you obtain by calling GetDeviceCaps(hdcPrimaryMonitor, HORZRES/VERTRES).
SM_CXSIZE,
SM_CYSIZE 		Width and height, in pixels, of a button in a window's caption or title bar.
SM_CXSIZEFRAME,
SM_CYSIZEFRAME 		Thickness, in pixels, of the sizing border around the perimeter of a window that can be resized. SM_CXSIZEFRAME is the width of the horizontal border, and SM_CYSIZEFRAME is the height of the vertical border.

Same as SM_CXFRAME and SM_CYFRAME.
SM_CXSMICON,
SM_CYSMICON 		Recommended dimensions, in pixels, of a small icon. Small icons typically appear in window captions and in small icon view.
SM_CXSMSIZE
SM_CYSMSIZE 		Dimensions, in pixels, of small caption buttons.
SM_CXVIRTUALSCREEN,
SM_CYVIRTUALSCREEN 		Windows 98/Me, Windows 2000 or later: Width and height, in pixels, of the virtual screen. The virtual screen is the bounding rectangle of all display monitors. The SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN metrics are the coordinates of the top-left corner of the virtual screen.
SM_CXVSCROLL,
SM_CYVSCROLL 		Width, in pixels, of a vertical scroll bar; and height, in pixels, of the arrow bitmap on a vertical scroll bar.
SM_CYCAPTION | Height, in pixels, of a normal caption area.
SM_CYKANJIWINDOW | For double byte character set versions of the system, this is the height, in pixels, of the Kanji window at the bottom of the screen.
SM_CYMENU | Height, in pixels, of a single-line menu bar.
SM_CYSMCAPTION | Height, in pixels, of a small caption.
SM_CYVTHUMB | Height, in pixels, of the thumb box in a vertical scroll bar.
SM_DBCSENABLED | TRUE or nonzero if the double-byte character-set (DBCS) version of User.exe is installed; FALSE or zero otherwise.
SM_DEBUG | TRUE or nonzero if the debugging version of User.exe is installed; FALSE or zero otherwise.
SM_IMMENABLED Windows 2000 and later: TRUE or nonzero if Input Method Manager/Input Method Editor features are enabled; FALSE or zero otherwise.

SM_IMMENABLED indicates whether the system is ready to use a Unicode-based IME on a Unicode application. To ensure that a language-dependent IME works, check SM_DBCSENABLED and the system ANSI code page. Otherwise the ANSI-to-Unicode conversion may not be performed correctly, or some components like fonts or registry setting may not be present.
SM_MENUDROPALIGNMENT | TRUE or nonzero if drop-down menus are right-aligned with the corresponding menu-bar item; FALSE or zero if the menus are left-aligned.
SM_MIDEASTENABLED | TRUE if the system is enabled for Hebrew and Arabic languages.
SM_MOUSEPRESENT | TRUE or nonzero if a mouse is installed; FALSE or zero otherwise.
SM_MOUSEWHEELPRESENT | Windows NT 4.0 and later, Windows 98/Me: TRUE or nonzero if a mouse with a wheel is installed; FALSE or zero otherwise.
SM_NETWORK | The least significant bit is set if a network is present; otherwise, it is cleared. The other bits are reserved for future use.
SM_PENWINDOWS | TRUE or nonzero if the Microsoft Windows for Pen computing extensions are installed; FALSE or zero otherwise.
SM_REMOTESESSION | Windows NT 4.0 SP4 and later: This system metric is used in a Terminal Services environment. If the calling process is associated with a Terminal Services client session, the return value is TRUE or nonzero. If the calling process is associated with the Terminal Server console session, the return value is zero.
SM_SECURE | TRUE if security is present; FALSE otherwise.
SM_SAMEDISPLAYFORMAT | Windows 98/Me, Windows 2000 or later: TRUE if all the display monitors have the same color format, FALSE otherwise. Note that two displays can have the same bit depth, but different color formats. For example, the red, green, and blue pixels can be encoded with different numbers of bits, or those bits can be located in different places in a pixel's color value.
SM_SHOWSOUNDS | TRUE or nonzero if the user requires an application to present information visually in situations where it would otherwise present the information only in audible form; FALSE, or zero, otherwise.
SM_SHUTTINGDOWN | Whistler: TRUE if the current session is shutting down; FALSE otherwise.
SM_SLOWMACHINE | TRUE if the computer has a low-end (slow) processor; FALSE otherwise.
SM_SWAPBUTTON | TRUE or nonzero if the meanings of the left and right mouse buttons are swapped; FALSE or zero otherwise.
SM_XVIRTUALSCREEN,
SM_YVIRTUALSCREEN 		Windows 98/Me, Windows 2000 or later: Coordinates for the left side and the top of the virtual screen. The virtual screen is the bounding rectangle of all display monitors. The SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN metrics are the width and height of the virtual screen.

Return Values

If the function succeeds, the return value is the requested system metric or configuration setting.

If the function fails, the return value is zero. GetLastError does not provide extended error information.

Remarks

System metrics may vary from display to display.

GetSystemMetrics(SM_CMONITORS) counts only display monitors. This is different from EnumDisplayMonitors which enumerates display monitors and also non-display pseudo-monitors.

The SM_ARRANGE setting specifies how the system arranges minimized windows, and consists of a starting position and a direction. The starting position can be one of the following values.

Value | Meaning
ARW_BOTTOMLEFT | Start at the lower-left corner of the screen (default position).
ARW_BOTTOMRIGHT | Start at the lower-right corner of the screen. Equivalent to ARW_STARTRIGHT.
ARW_HIDE | Hide minimized windows by moving them off the visible area of the screen.
ARW_TOPLEFT | Start at the upper-left corner of the screen. Equivalent to ARV_STARTTOP.
ARW_TOPRIGHT | Start at the upper-right corner of the screen. Equivalent to ARW_STARTTOP | SRW_STARTRIGHT.

The direction in which to arrange can be one of the following values.

Value | Meaning
ARW_DOWN | Arrange vertically, top to bottom.
ARW_LEFT | Arrange horizontally, left to right.
ARW_RIGHT | Arrange horizontally, right to left.
ARW_UP | Arrange vertically, bottom to top.

For an example, see Getting Hardware Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

System Information Overview, System Information Functions, EnumDisplayMonitors, SystemParametersInfo


GetSystemWindowsDirectory

The GetSystemWindowsDirectory function retrieves the path of the shared Windows directory on a multiuser system.

UINT GetSystemWindowsDirectory(
  LPTSTR lpBuffer,  // buffer to receive directory name
  UINT uSize        // size of name buffer
);

Parameters

lpBuffer
[out] Pointer to the buffer to receive a null-terminated string containing the path. This path does not end with a backslash unless the Windows directory is the root directory. For example, if the Windows directory is named WINDOWS on drive C, the path of the Windows directory retrieved by this function is C:\WINDOWS. If the system was installed in the root directory of drive C, the path retrieved is C:\.
uSize
[in] Specifies the maximum size, in TCHARs, of the buffer specified by the lpBuffer parameter. This value should be set to at least MAX_PATH to allow sufficient room in the buffer for the path.

Return Values

If the function succeeds, the return value is the length, in TCHARs, of the string copied to the buffer, not including the terminating null character.

If the length is greater than the size of the buffer, the return value is the size of the buffer required to hold the path.

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

Remarks

The system Windows directory is the directory where an application should store initialization and help files that apply to all users.

On a single-user system, GetSystemWindowsDirectory is the same as the GetWindowsDirectory function. However, on a multiuser system, the GetSystemWindowsDirectory function retrieves the path of the Windows directory used by the system (that is, shared by all users), and GetWindowsDirectory retrieves the path of a Windows directory that is private for each user.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, GetWindowsDirectory, SHGetFolderLocation


GetSystemWow64Directory

[This is preliminary documentation and subject to change.]

The GetSystemWow64Directory function retrieves the path of the system directory used by WOW64. This directory is not present on 32-bit Windows.

UINT GetSystemWow64Directory(
  LPTSTR lpBuffer,  // buffer for system directory
  UINT uSize        // size of directory buffer
);

Parameters

lpBuffer
[out] Pointer to the buffer to receive the null-terminated string containing the path. This path does not end with a backslash.
uSize
[in] Specifies the maximum size of the buffer, in TCHARs. This value should be set to at least MAX_PATH.

Return Values

If the function succeeds, the return value is the length, in TCHARs, of the string copied to the buffer, not including the terminating null character. If the length is greater than the size of the buffer, the return value is the size of the buffer required to hold the path.

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

On 32-bit Windows, the function always fails, and the extended error is set to ERROR_CALL_NOT_IMPLEMENTED.

Remarks

WOW64 uses the system directory to store shared 32-bit code on 64-bit Windows. Most applications have no need to access this directory explicitly.

For more information on WOW64, see Running 32-bit Applications.

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Whistler.

See Also

System Information Overview, System Information Functions


GetUserName

The GetUserName function retrieves the user name of the current thread. This is the name of the user currently logged onto the system.

Windows 2000 and later: Use the GetUserNameEx function to retrieve the user name in a specified format. Additional information is provided by the IADsADSystemInfo interface.

BOOL GetUserName(
  LPTSTR lpBuffer,  // name buffer
  LPDWORD nSize     // size of name buffer
);

Parameters

lpBuffer
[out] Pointer to the buffer to receive the null-terminated string containing the user's logon name. If this buffer is not large enough to contain the entire user name, the function fails. A buffer size of (UNLEN + 1) characters will hold the maximum length user name including the terminating null character. UNLEN is defined in Lmcons.h.
nSize
[in/out] On input, specifies the maximum size, in TCHARs, of the buffer specified by the lpBuffer parameter. On output, receives the number of characters copied to the buffer.

If the buffer is not large enough, the function fails and nSize receives the required buffer size, in TCHARs, including the terminating null character.

Return Values

If the function succeeds, the return value is a nonzero value, and the variable pointed to by nSize contains the number of TCHARs copied to the buffer specified by lpBuffer, including the terminating null character.

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

Remarks

If the current thread is impersonating another client, the GetUserName function returns the user name of the client that the thread is impersonating.

For an example, see Getting System Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, GetUserNameEx, LookupAccountName


GetUserNameEx

The GetUserNameEx function retrieves the name of the user or other security principal associated with the calling thread. You can specify the format of the returned name.

If the thread is impersonating a client, GetUserNameEx returns the name of the client.

BOOLEAN GetUserNameEx(
  EXTENDED_NAME_FORMAT NameFormat,  // name format
  LPTSTR lpNameBuffer,              // name buffer
  PULONG nSize                      // size of name buffer
);

Parameters

NameFormat
[in] Value from the EXTENDED_NAME_FORMAT enumeration type indicating the desired name format. This value cannot be NameUnknown.
lpNameBuffer
[out] Pointer to a buffer that receives the name in the specified format.
nSize
[in/out] On input, specifies the size, in TCHARs, of the lpNameBuffer buffer. On output, receives the size of the returned string, including the terminating null character.

If the lpNameBuffer buffer is too small to hold the name, the function fails and nSize receives the required buffer size.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Secext.h; include Security.h.
Library: Use Secur32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

System Information Overview, System Information Functions, EXTENDED_NAME_FORMAT, GetUserName


GetVersion

The GetVersion function returns the current version number of the operating system.

Note This function has been superseded by GetVersionEx. New applications should use GetVersionEx or VerifyVersionInfo.

DWORD GetVersion(VOID);

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is a DWORD value that contains the major and minor version numbers of the operating system in the low order word, and information about the operating system platform in the high order word.

For all platforms, the low order word contains the version number of the operating system. The low-order byte of this word specifies the major version number, in hexadecimal notation. The high-order byte specifies the minor version (revision) number, in hexadecimal notation.

To distinguish between operating system platforms, use the high order bit and the low order byte, as shown in the following table:

Platform | High-order bit | Next 7 bits | Low-order byte
Windows NT 3.51 | 0 | Build number | 3
Windows NT 4.0 | 0 | Build number | 4
Windows 2000 or Whistler | 0 | Build number | 5
Windows 95, Windows 98, or Windows Me | 1 | Reserved | 4
Win32s with Windows 3.1 | 1 | Build number | 3

Remarks

The GetVersionEx function was developed because many existing applications err when examining the packed DWORD value returned by GetVersion, transposing the major and minor version numbers. GetVersionEx forces applications to explicitly examine each element of version information. VerifyVersionInfo eliminates further potential for error by comparing the required system version with the current system version for you.

The following code fragment illustrates how to extract information from the GetVersion return value:

dwVersion = GetVersion();

// Get the Windows version.

dwWindowsMajorVersion =  (DWORD)(LOBYTE(LOWORD(dwVersion)));
dwWindowsMinorVersion =  (DWORD)(HIBYTE(LOWORD(dwVersion)));

// Get the build number.

if (dwVersion < 0x80000000)              // Windows NT/2000, Whistler
    dwBuild = (DWORD)(HIWORD(dwVersion));
else if (dwWindowsMajorVersion < 4)      // Win32s
    dwBuild = (DWORD)(HIWORD(dwVersion) & ~0x8000);
else                                     // Windows 95/98/Me
    dwBuild =  0;

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, GetVersionEx, VerifyVersionInfo


GetVersionEx

The GetVersionEx function obtains extended information about the version of the operating system that is currently running.

Windows 2000 or later: To compare the current system version to a required version, use the VerifyVersionInfo function instead of using GetVersionEx to perform the comparison yourself.

BOOL GetVersionEx(
  LPOSVERSIONINFO lpVersionInfo // version information
);

Parameters

lpVersionInfo
[in/out] Pointer to an OSVERSIONINFO data structure that the function fills with operating system version information.

Before calling the GetVersionEx function, set the dwOSVersionInfoSize member of the OSVERSIONINFO data structure to sizeof(OSVERSIONINFO).

Windows NT 4.0 SP6 and later: This member can be a pointer to an OSVERSIONINFOEX structure. Set the dwOSVersionInfoSize member to sizeof(OSVERSIONINFOEX) to identify the structure type.

Return Values

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError. The function fails if you specify an invalid value for the dwOSVersionInfoSize member of the OSVERSIONINFO or OSVERSIONINFOEX structure.

Remarks

When using the GetVersionEx function to determine whether your application is running on a particular version of the operating system, check for version numbers that are greater than or equal to the desired version numbers. This ensures that the test succeeds for later versions of the operating system. For example, if your application requires Windows 98, use the following test:

osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO)
GetVersionEx (&osvi);
bIsWindows98orLater =
   (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) &&
   ( (osvi.dwMajorVersion > 4) ||
   ( (osvi.dwMajorVersion == 4) && (osvi.dwMinorVersion > 0) ) );

Identifying the current operating system is usually not the best way to determine whether a particular operating system feature is present. This is because the operating system may have had new features added in a redistributable DLL. Rather than using GetVersionEx to determine the operating system platform or version number, test for the presence of the feature itself. For more information, see Operating System Version.

Example

For an example, see Getting the System Version.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, GetVersion, OSVERSIONINFO, OSVERSIONINFOEX, VerifyVersionInfo


GetWindowsDirectory

The GetWindowsDirectory function retrieves the path of the Windows directory. The Windows directory contains such files as applications, initialization files, and help files.

UINT GetWindowsDirectory(
  LPTSTR lpBuffer,  // buffer for Windows directory
  UINT uSize        // size of directory buffer
);

Parameters

lpBuffer
[out] Pointer to the buffer to receive the null-terminated string containing the path. This path does not end with a backslash unless the Windows directory is the root directory. For example, if the Windows directory is named WINDOWS on drive C, the path of the Windows directory retrieved by this function is C:\WINDOWS. If the system was installed in the root directory of drive C, the path retrieved is C:\.
uSize
[in] Specifies the maximum size, in TCHARs, of the buffer specified by the lpBuffer parameter. This value should be set to MAX_PATH to allow sufficient room for the path.

Return Values

If the function succeeds, the return value is the length, in TCHARs, of the string copied to the buffer, not including the terminating null character.

If the length is greater than the size of the buffer, the return value is the size of the buffer required to hold the path.

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

Remarks

The Windows directory is the directory where an application should store initialization and help files. If the user is running a shared version of the system, the Windows directory is guaranteed to be private for each user.

If an application creates other files that it wants to store on a per-user basis, it should place them in the directory specified by the HOMEPATH environment variable. This directory will be different for each user, if so specified by an administrator, through the User Manager administrative tool. HOMEPATH always specifies either the user's home directory, which is guaranteed to be private for each user, or a default directory (for example, C:\USERS\DEFAULT) where the user will have all access.

Terminal Services: If the application is running in a Terminal Services environment, each user has a unique Windows directory. If an application that is not Terminal-Services-aware calls this function, it retrieves the path of the Windows directory on the client, not the Windows directory on the server.

For an example, see Getting System Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, GetCurrentDirectory, GetSystemDirectory, GetSystemWindowsDirectory


IsProcessorFeaturePresent

The IsProcessorFeaturePresent function determines whether the specified processor feature is supported by the current computer.

BOOL IsProcessorFeaturePresent(
  DWORD ProcessorFeature  // processor feature
);

Parameters

ProcessorFeature
[in] Specifies the processor feature to be tested. This parameter can be one of the following values.
Value | Meaning
PF_FLOATING_POINT_PRECISION_ERRATA | In rare circumstances, a floating-point precision error can occur (Pentium).
PF_FLOATING_POINT_EMULATED Floating-point operations are emulated using a software emulator.

Windows 2000 and later: This function returns a nonzero value if floating-point operations are emulated; otherwise, it returns zero.

Windows NT 4.0: This function returns zero if floating-point operations are emulated; otherwise, it returns a nonzero value. This behavior is a bug that is fixed in later versions.
PF_COMPARE_EXCHANGE_DOUBLE | The compare and exchange double operation is available (Pentium, MIPS, and Alpha).
PF_MMX_INSTRUCTIONS_AVAILABLE | The MMX instruction set is available.
PF_XMMI_INSTRUCTIONS_AVAILABLE | The XMMI instruction set is available.
PF_3DNOW_INSTRUCTIONS_AVAILABLE | The 3D-Now instruction set is available.
PF_RDTSC_INSTRUCTION_AVAILABLE | The RDTSC instruction is available.
PF_PAE_ENABLED | The processor is PAE-enabled.

Return Values

If feature is supported, the return value is a nonzero value.

If the feature is not supported, the return value is zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

System Information Overview, System Information Functions


SetComputerName

The SetComputerName function stores a new NetBIOS name for the local computer. The name is stored in the registry and takes effect the next time the user restarts the computer.

If the local computer is a node in a cluster, SetComputerName sets NetBIOS name of the local computer, not that of the cluster.

Windows 2000 or later: To set the DNS host name or the DNS domain name, call the SetComputerNameEx function.

BOOL SetComputerName(
  LPCTSTR lpComputerName  // computer name
);

Parameters

lpComputerName
[in] Pointer to a null-terminated character string that specifies the name that will be the computer name the next time the computer is started. The name must not be longer than MAX_COMPUTERNAME_LENGTH characters.

Windows 95/98/Me: If this string contains one or more characters that are outside the standard character set, those characters are coerced into standard characters.

Windows NT/2000 or later: If this string contains one or more characters that are outside the standard character set, SetComputerName returns ERROR_INVALID_PARAMETER. It does not coerce the characters outside the standard set.

The standard character set includes letters, numbers, and the following symbols: ! @ # $ % ^ & ' ) ( . - _ { } ~ .

Return Values

If the function succeeds, the return value is a nonzero value.

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

Remarks

Applications using this function must have administrator rights.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, GetComputerName, GetComputerNameEx, SetComputerNameEx


SetComputerNameEx

The SetComputerNameEx function sets a NetBIOS or DNS name for the local computer. Name changes made by SetComputerNameEx do not take effect until the user restarts the computer.

SetComputerNameEx can set the NetBIOS name, which can also be set using the SetComputerName function. In addition, SetComputerNameEx can set the DNS host name or DNS domain name of the local computer. It cannot set a fully-qualified DNS name.

If the local computer is a node in a cluster, SetComputerNameEx sets NetBIOS or DNS name of the local computer, not that of the cluster.

BOOL SetComputerNameEx(
  COMPUTER_NAME_FORMAT NameType,  // name type
  LPCTSTR lpBuffer                // new name buffer
);

Parameters

NameType
[in] Specifies the type of name to set. This parameter can be one of the following values from the COMPUTER_NAME_FORMAT enumeration type.
Value | Description
ComputerNamePhysicalNetBIOS Sets the NetBIOS name to the name specified in lpBuffer. The name cannot exceed MAX_COMPUTERNAME_LENGTH characters, not including the terminating null character.

Warning: Using this option to set the NetBIOS name breaks the convention of interdependent NetBIOS and DNS names. Applications that use the DnsHostnameToComputerName function will fail if this convention is broken.
ComputerNamePhysicalDnsHostname | Sets the NetBIOS and the DNS host name name to the name specified in lpBuffer. If the name exceeds MAX_COMPUTERNAME_LENGTH characters, the NetBIOS name is truncated to MAX_COMPUTERNAME_LENGTH characters, not including the terminating null character.
ComputerNamePhysicalDnsDomain | Sets the name of the DNS domain assigned to the computer.

lpBuffer
[in] Pointer to a null-terminated string that specifies the new name. The name cannot include control characters, leading or trailing spaces, or any of the following characters: " / \ [ ] : | < > + = ; , ?

Return Value

If the function succeeds, the return value is a nonzero value.

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

Remarks

The process that calls the SetComputerNameEx function must have administrator privileges on the local computer.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

System Information Overview, System Information Functions, COMPUTER_NAME_FORMAT, DnsHostnameToComputerName, GetComputerName, GetComputerNameEx, SetComputerName


SetSysColors

The SetSysColors function sets the colors for one or more display elements. Display elements are the various parts of a window and the display that appear on the system display screen.

BOOL SetSysColors(
  int cElements,                 // number of elements
  CONST INT *lpaElements,        // array of elements
  CONST COLORREF *lpaRgbValues   // array of RGB values
);

Parameters

cElements
[in] Specifies the number of display elements in the array pointed to by the lpaElements parameter.
lpaElements
[in] Pointer to an array of integers that specify the display elements to be changed. For a list of display elements, see GetSysColor.
lpaRgbValues
[in] Pointer to an array of COLORREF values that contain the new red, green, blue (RGB) color values for the display elements in the array pointed to by the lpaElements parameter. To generate a COLORREF, use the RGB macro.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Remarks

The SetSysColors function sends a WM_SYSCOLORCHANGE message to all windows to inform them of the change in color. It also directs the system to repaint the affected portions of all currently visible windows.

The SetSysColors function changes the current session only. The new colors are not saved when the system terminates.

For an example, see Changing the Colors of Window Elements.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

System Information Overview, System Information Functions, GetSysColor, COLORREF, RGB


SystemParametersInfo

The SystemParametersInfo function retrieves or sets the value of one of the system-wide parameters. This function can also update the user profile while setting a parameter.

BOOL SystemParametersInfo(
  UINT uiAction,  // system parameter to retrieve or set
  UINT uiParam,   // depends on action to be taken
  PVOID pvParam,  // depends on action to be taken
  UINT fWinIni    // user profile update option
);

Parameters

uiAction
[in] Specifies the system-wide parameter to retrieve or set. This parameter can be one of the values from the following tables.

The following are the accessibility parameters.
Accessibility parameter | Meaning
SPI_GETACCESSTIMEOUT | Retrieves information about the time-out period associated with the accessibility features. The pvParam parameter must point to an ACCESSTIMEOUT structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(ACCESSTIMEOUT).
SPI_GETFILTERKEYS | Retrieves information about the FilterKeys accessibility feature. The pvParam parameter must point to a FILTERKEYS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(FILTERKEYS).
SPI_GETFOCUSBORDERHEIGHT | Whistler: Gets the height, in pixels, of the top and bottom edges of the focus rectangle drawn with DrawFocusRect. The pvParam parameter must point to a UINT.
SPI_GETFOCUSBORDERWIDTH | Whistler: Gets the width, in pixels, of the left and right edges of the focus rectangle drawn with DrawFocusRect. The pvParam parameter must point to a UINT.
SPI_GETHIGHCONTRAST | Windows 95/98, Windows 2000 or later: Retrieves information about the HighContrast accessibility feature. The pvParam parameter must point to a HIGHCONTRAST structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(HIGHCONTRAST).
SPI_GETMOUSECLICKLOCK | Windows Me and Whistler: Gets the state of the Mouse ClickLock feature. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE otherwise. For more information, see About Mouse Input.
SPI_GETMOUSECLICKLOCKTIME | Windows Me and Whistler: Gets the time delay before the primary mouse button is locked. The pvParam parameter must point to DWORD that receives the time delay. This is only enabled if SPI_SETMOUSECLICKLOCK is set to TRUE. For more information, see About Mouse Input.
SPI_GETMOUSEKEYS | Retrieves information about the MouseKeys accessibility feature. The pvParam parameter must point to a MOUSEKEYS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(MOUSEKEYS).
SPI_GETMOUSESONAR | Windows Me and Whistler: Gets the state of the Mouse Sonar feature. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled or FALSE otherwise. For more information, see About Mouse Input.
SPI_GETMOUSEVANISH | Windows Me and Whistler: Gets the state of the Mouse Vanish feature. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled or FALSE otherwise. For more information, see About Mouse Input.
SPI_GETSCREENREADER Windows 95/98, Windows 2000 or later: Determines whether a screen reviewer utility is running. A screen reviewer utility directs textual information to an output device, such as a speech synthesizer or Braille display. When this flag is set, an application should provide textual information in situations where it would otherwise present the information graphically.

The pvParam parameter is a pointer to a BOOL variable that receives TRUE if a screen reviewer utility is running, or FALSE otherwise.
SPI_GETSERIALKEYS Windows 95/98/Me: Retrieves information about the SerialKeys accessibility feature. The pvParam parameter must point to a SERIALKEYS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(SERIALKEYS).

Windows NT/2000 or later: Not supported.

SPI_GETSHOWSOUNDS Determines whether the Show Sounds accessibility flag is on or off. If it is on, the user requires an application to present information visually in situations where it would otherwise present the information only in audible form. The pvParam parameter must point to a BOOL variable that receives TRUE if the feature is on, or FALSE if it is off.

Using this value is equivalent to calling GetSystemMetrics (SM_SHOWSOUNDS). That is the recommended call.
SPI_GETSOUNDSENTRY | Retrieves information about the SoundSentry accessibility feature. The pvParam parameter must point to a SOUNDSENTRY structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(SOUNDSENTRY).
SPI_GETSTICKYKEYS | Retrieves information about the StickyKeys accessibility feature. The pvParam parameter must point to a STICKYKEYS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(STICKYKEYS).
SPI_GETTOGGLEKEYS | Retrieves information about the ToggleKeys accessibility feature. The pvParam parameter must point to a TOGGLEKEYS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(TOGGLEKEYS).
SPI_SETACCESSTIMEOUT | Sets the time-out period associated with the accessibility features. The pvParam parameter must point to an ACCESSTIMEOUT structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(ACCESSTIMEOUT).
SPI_SETFILTERKEYS | Sets the parameters of the FilterKeys accessibility feature. The pvParam parameter must point to a FILTERKEYS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(FILTERKEYS).
SPI_SETFOCUSBORDERHEIGHT | Whistler: Sets the height of the top and bottom edges of the focus rectangle drawn with DrawFocusRect to the value of the pvParam parameter.
SPI_SETFOCUSBORDERWIDTH | Whistler: Sets the height of the left and right edges of the focus rectangle drawn with DrawFocusRect to the value of the pvParam parameter.
SPI_SETHIGHCONTRAST | Windows 95/98, Windows 2000 or later: Sets the parameters of the HighContrast accessibility feature. The pvParam parameter must point to a HIGHCONTRAST structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(HIGHCONTRAST).
SPI_SETMOUSECLICKLOCK | Windows Me and Whistler: Turns the Mouse ClickLock accessibility feature on or off. This feature temporarily locks down the primary mouse button when that button is clicked and held down for the time specified by SPI_SETMOUSECLICKLOCKTIME. The uiParam parameter specifies TRUE for on, or FALSE for off. The default is off. For more information, see Remarks and About Mouse Input.
SPI_SETMOUSECLICKLOCKTIME | Windows Me and Whistler: Adjusts the time delay before the primary mouse button is locked. The uiParam parameter specifies the time delay in microseconds. For example, specify 1000 for a 1 second delay. The default is 1200. For more information, see About Mouse Input.
SPI_SETMOUSEKEYS | Sets the parameters of the MouseKeys accessibility feature. The pvParam parameter must point to a MOUSEKEYS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(MOUSEKEYS).
SPI_SETMOUSESONAR | Windows Me and Whistler: Turns the Sonar accessibility feature on or off. This feature briefly shows several concentric circles around the mouse pointer when the user presses and releases the CTRL key. The uiParam parameter specifies TRUE for on and FALSE for off. The default is off. For more information, see About Mouse Input.
SPI_SETMOUSEVANISH | Windows Me and Whistler: Turns the Vanish feature on or off. This feature hides the mouse pointer when the user types; the pointer reappears when the user moves the mouse. The uiParam parameter specifies TRUE for on and FALSE for off. The default is off. For more information, see About Mouse Input.
SPI_SETSCREENREADER | Windows 95/98, Windows 2000 or later: Indicates whether a screen review utility is running. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETSERIALKEYS | Windows 95/98/Me: Sets the parameters of the SerialKeys accessibility feature. The pvParam parameter must point to a SERIALKEYS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(SERIALKEYS). Windows NT/2000 or later: Not supported.
SPI_SETSHOWSOUNDS | Sets the ShowSounds accessibility feature as on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETSOUNDSENTRY | Sets the parameters of the SoundSentry accessibility feature. The pvParam parameter must point to a SOUNDSENTRY structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(SOUNDSENTRY).
SPI_SETSTICKYKEYS | Sets the parameters of the StickyKeys accessibility feature. The pvParam parameter must point to a STICKYKEYS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(STICKYKEYS).
SPI_SETTOGGLEKEYS | Sets the parameters of the ToggleKeys accessibility feature. The pvParam parameter must point to a TOGGLEKEYS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(TOGGLEKEYS).

The following are the desktop parameters.
Desktop parameter | Meaning
SPI_GETDESKWALLPAPER | Windows 2000 and later: Retrieves the full path of the bitmap file for the desktop wallpaper. The pvParam parameter must point to a buffer that receives a null-terminated path string. Set the uiParam parameter to the size, in characters, of the pvParam buffer. The returned string will not exceed MAX_PATH characters. If there is no desktop wallpaper, the returned string is empty.
SPI_GETDROPSHADOW | Whistler: Indicates whether the drop shadow effect is enabled. The pvParam parameter must point to a BOOL variable that returns TRUE if enabled or FALSE if disabled.
SPI_GETFLATMENU | Whistler: Indicates whether native User menus have flat menu appearance. The pvParam parameter must point to a BOOL variable that returns TRUE if the flat menu appearance is set, or FALSE otherwise.
SPI_GETFONTSMOOTHING Indicates whether the font smoothing feature is enabled. This feature uses font antialiasing to make font curves appear smoother by painting pixels at different gray levels.

The pvParam parameter must point to a BOOL variable that receives TRUE if the feature is enabled, or FALSE if it is not.

Windows 95: This flag is supported only if Windows Plus! is installed. See SPI_GETWINDOWSEXTENSION.
SPI_GETFONTSMOOTHINGCONTRAST | Whistler: Returns a contrast value that is used in ClearType™ smoothing. The pvParam parameter must point to a UINT that receives the information.
SPI_GETFONTSMOOTHINGTYPE | Whistler: Returns the type of font smoothing. The pvParam parameter must point to a UINT that receives the information.
SPI_GETWORKAREA Retrieves the size of the work area on the primary display monitor. The work area is the portion of the screen not obscured by the system taskbar or by application desktop toolbars. The pvParam parameter must point to a RECT structure that receives the coordinates of the work area, expressed in virtual screen coordinates.

To get the work area of a monitor other than the primary display monitor, call the GetMonitorInfo function.
SPI_SETCURSORS | Reloads the system cursors. Set the uiParam parameter to zero and the pvParam parameter to NULL
SPI_SETDESKPATTERN | Sets the current desktop pattern by causing Windows to read the Pattern= setting from the WIN.INI file.
SPI_SETDESKWALLPAPER | Sets the desktop wallpaper. The value of the pvParam parameter determines the new wallpaper. To specify a wallpaper bitmap, set pvParam to point to a null-terminated string containing the name of a bitmap file. Setting pvParam to "" removes the wallpaper. Setting pvParam to SETWALLPAPER_DEFAULT or NULL reverts to the default wallpaper.
SPI_SETDROPSHADOW | Whistler: Enables or disables the drop shadow effect. Set pvParam to TRUE to enable the drop shadow effect or FALSE to disable it. You must also have CS_DROPSHADOW in the window class style.
SPI_SETFLATMENU Whistler: Enables or disables flat menu appearance for native User menus. Set pvParam to TRUE to enable flat menu appearance or FALSE to disable it.

When enabled, the menu bar uses COLOR_MENUBAR for the menubar background, COLOR_MENU for the menu-popup background, COLOR_MENUHILIGHT for the fill of the current menu selection, and COLOR_HILIGHT for the outline of the current menu selection. If disabled, menus are drawn using the same metrics and colors as in Windows 2000 and earlier.
SPI_SETFONTSMOOTHING Enables or disables the font smoothing feature, which uses font antialiasing to make font curves appear smoother by painting pixels at different gray levels.

To enable the feature, set the uiParam parameter to TRUE. To disable the feature, set uiParam to FALSE.

Windows 95: This flag is supported only if Windows Plus! is installed. See SPI_GETWINDOWSEXTENSION.
SPI_SETFONTSMOOTHINGCONTRAST Whistler: Changes the contrast value used in ClearType smoothing. The pvParam parameter points to a UINT that holds the contrast value. Valid contrast values are from 1000 to 2200. The default value is 1400.

SPI_SETFONTSMOOTHINGTYPE must also be set to FE_FONTSMOOTHINGCLEARTYPE.
SPI_SETFONTSMOOTHINGTYPE Whistler: Changes the font smoothing type. The pvParam parameter points to a UINT that contains either FE_FONTSMOOTHINGSTANDARD, if standard anti-aliasing is used, or FE_FONTSMOOTHINGCLEARTYPE, if ClearType is used. The default is FE_FONTSMOOTHINGSTANDARD.

SPI_SETFONTSMOOTHING must also be set.
SPI_SETWORKAREA Sets the size of the work area. The work area is the portion of the screen not obscured by the system taskbar or by application desktop toolbars. The pvParam parameter is a pointer to a RECT structure that specifies the new work area rectangle, expressed in virtual screen coordinates. In a system with multiple display monitors, the function sets the work area of the monitor that contains the specified rectangle.

If pvParam is NULL, the function sets the work area of the primary display monitor to the full screen.

The following are the icon parameters.
Icon parameter | Meaning
SPI_GETICONMETRICS | Retrieves the metrics associated with icons. The pvParam parameter must point to an ICONMETRICS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(ICONMETRICS).
SPI_GETICONTITLELOGFONT | Retrieves the logical font information for the current icon-title font. The uiParam parameter specifies the size of a LOGFONT structure, and the pvParam parameter must point to the LOGFONT structure to fill in.
SPI_GETICONTITLEWRAP | Determines whether icon-title wrapping is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE otherwise.
SPI_ICONHORIZONTALSPACING Sets or retrieves the width, in pixels, of an icon cell. The system uses this rectangle to arrange icons in large icon view.

To set this value, set uiParam to the new value and set pvParam to NULL. You cannot set this value to less than SM_CXICON.

To retrieve this value, pvParam must point to an integer that receives the current value.

SPI_ICONVERTICALSPACING Sets or retrieves the height, in pixels, of an icon cell.

To set this value, set uiParam to the new value and set pvParam to NULL. You cannot set this value to less than SM_CYICON.

To retrieve this value, pvParam must point to an integer that receives the current value.

SPI_SETICONMETRICS | Sets the metrics associated with icons. The pvParam parameter must point to an ICONMETRICS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(ICONMETRICS).
SPI_SETICONS | Reloads the system icons. Set the uiParam parameter to zero and the pvParam parameter to NULL
SPI_SETICONTITLELOGFONT | Sets the font that is used for icon titles. The uiParam parameter specifies the size of a LOGFONT structure, and the pvParam parameter must point to a LOGFONT structure.
SPI_SETICONTITLEWRAP | Turns icon-title wrapping on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.

The following are the input parameters. They include parameters related to the keyboard, mouse, input language, and the warning beeper.
Input parameter | Meaning
SPI_GETBEEP Indicates whether the warning beeper is on.

The pvParam parameter must point to a BOOL variable that receives TRUE if the beeper is on, or FALSE if it is off.
SPI_GETDEFAULTINPUTLANG | Returns the input locale identifier for the system default input language. The pvParam parameter must point to an HKL variable that receives this value. For more information, see Languages, Locales, and Keyboard Layouts.
SPI_GETKEYBOARDCUES | Windows 98/Me, Windows 2000 or later: Indicates whether menu access keys are always underlined. The pvParam parameter must point to a BOOL variable that receives TRUE if menu access keys are always underlined, and FALSE if they are underlined only when the menu is activated by the keyboard.
SPI_GETKEYBOARDDELAY | Retrieves the keyboard repeat-delay setting, which is a value in the range from 0 (approximately 250 ms delay) through 3 (approximately 1 second delay). The actual delay associated with each value may vary depending on the hardware. The pvParam parameter must point to an integer variable that receives the setting.
SPI_GETKEYBOARDPREF | Windows 95/98, Windows 2000 or later: Determines whether the user relies on the keyboard instead of the mouse, and wants applications to display keyboard interfaces that would otherwise be hidden. The pvParam parameter must point to a BOOL variable that receives TRUE if the user relies on the keyboard; or FALSE otherwise.
SPI_GETKEYBOARDSPEED | Retrieves the keyboard repeat-speed setting, which is a value in the range from 0 (approximately 2.5 repetitions per second) through 31 (approximately 30 repetitions per second). The actual repeat rates are hardware-dependent and may vary from a linear scale by as much as 20%. The pvParam parameter must point to a DWORD variable that receives the setting.
SPI_GETMOUSE | Retrieves the two mouse threshold values and the mouse acceleration. The pvParam parameter must point to an array of three integers that receives these values. See mouse_event for further information.
SPI_GETMOUSEHOVERHEIGHT Gets the height, in pixels, of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message. The pvParam parameter must point to a UINT variable that receives the height.

Windows 95: Not supported.
SPI_GETMOUSEHOVERTIME Gets the time, in milliseconds, that the mouse pointer has to stay in the hover rectangle for TrackMouseEvent to generate a WM_MOUSEHOVER message. The pvParam parameter must point to a UINT variable that receives the time.

Windows 95: Not supported.
SPI_GETMOUSEHOVERWIDTH Gets the width, in pixels, of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message. The pvParam parameter must point to a UINT variable that receives the width.

Windows 95: Not supported.
SPI_GETMOUSESPEED | Windows 98/Me, Windows 2000 or later: Retrieves the current mouse speed. The mouse speed determines how far the pointer will move based on the distance the mouse moves. The pvParam parameter must point to an integer that receives a value which ranges between 1 (slowest) and 20 (fastest). A value of 10 is the default. The value can be set by an end user using the mouse control panel application or by an application using SPI_SETMOUSESPEED.
SPI_GETMOUSETRAILS Windows 95/98 and Whistler: Indicates whether the Mouse Trails feature is enabled. This feature improves the visibility of mouse cursor movements by briefly showing a trail of cursors and quickly erasing them.

The pvParam parameter must point to an integer variable that receives a value. If the value is zero or 1, the feature is disabled. If the value is greater than 1, the feature is enabled and the value indicates the number of cursors drawn in the trail. The uiParam parameter is not used.

Windows NT/2000 or later: Not supported.

SPI_GETSNAPTODEFBUTTON Determines whether the snap-to-default-button feature is enabled. If enabled, the mouse cursor automatically moves to the default button, such as OK or Apply, of a dialog box. The pvParam parameter must point to a BOOL variable that receives TRUE if the feature is on, or FALSE if it is off.

Windows 95: Not supported.
SPI_GETWHEELSCROLLLINES Gets the number of lines to scroll when the mouse wheel is rotated. The pvParam parameter must point to a UINT variable that receives the number of lines. The default value is 3.

Windows 95: Not supported.
SPI_SETBEEP | Turns the warning beeper on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.
SPI_SETDEFAULTINPUTLANG | Sets the default input language for the system shell and applications. The specified language must be displayable using the current system character set. The pvParam parameter must point to an HKL variable that contains the input locale identifier for the default language. For more information, see Languages, Locales, and Keyboard Layouts.
SPI_SETDOUBLECLICKTIME | Sets the double-click time for the mouse to the value of the uiParam parameter. The double-click time is the maximum number of milliseconds that can occur between the first and second clicks of a double-click. You can also call the SetDoubleClickTime function to set the double-click time. To get the current double-click time, call the GetDoubleClickTime function.
SPI_SETDOUBLECLKHEIGHT Sets the height of the double-click rectangle to the value of the uiParam parameter.

The double-click rectangle is the rectangle within which the second click of a double-click must fall for it to be registered as a double-click.

To retrieve the height of the double-click rectangle, call GetSystemMetrics with the SM_CYDOUBLECLK flag.
SPI_SETDOUBLECLKWIDTH Sets the width of the double-click rectangle to the value of the uiParam parameter.

The double-click rectangle is the rectangle within which the second click of a double-click must fall for it to be registered as a double-click.

To retrieve the width of the double-click rectangle, call GetSystemMetrics with the SM_CXDOUBLECLK flag.
SPI_SETKEYBOARDCUES | Windows 98/Me, Windows 2000 or later: Sets the underlining of menu access key letters. The pvParam parameter is a BOOL variable. Set pvParam to TRUE to always underline menu access keys, or FALSE to underline menu access keys only when the menu is activated from the keyboard.
SPI_SETKEYBOARDDELAY | Sets the keyboard repeat-delay setting. The uiParam parameter must specify 0, 1, 2, or 3, where zero sets the shortest delay (approximately 250 ms) and 3 sets the longest delay (approximately 1 second). The actual delay associated with each value may vary depending on the hardware.
SPI_SETKEYBOARDPREF | Windows 95/98, Windows 2000 or later: Sets the keyboard preference. The uiParam parameter specifies TRUE if the user relies on the keyboard instead of the mouse, and wants applications to display keyboard interfaces that would otherwise be hidden; uiParam is FALSE otherwise.
SPI_SETKEYBOARDSPEED | Sets the keyboard repeat-speed setting. The uiParam parameter must specify a value in the range from 0 (approximately 2.5 repetitions per second) through 31 (approximately 30 repetitions per second). The actual repeat rates are hardware-dependent and may vary from a linear scale by as much as 20%. If uiParam is greater than 31, the parameter is set to 31.
SPI_SETLANGTOGGLE | Sets the hot key set for switching between input languages. The uiParam and pvParam parameters are not used. The value sets the shortcut keys in the keyboard property sheets by reading the registry again. The registry must be set before this flag is used. the path in the registry is \HKEY_CURRENT_USER\keyboard layout\toggle. Valid values are "1" = ALT+SHIFT, "2" = CTRL+SHIFT, and "3" = none.
SPI_SETMOUSE | Sets the two mouse threshold values and the mouse acceleration. The pvParam parameter must point to an array of three integers that specifies these values. See mouse_event for further information.
SPI_SETMOUSEBUTTONSWAP | Swaps or restores the meaning of the left and right mouse buttons. The uiParam parameter specifies TRUE to swap the meanings of the buttons, or FALSE to restore their original meanings.
SPI_SETMOUSEHOVERHEIGHT Sets the height, in pixels, of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message. Set the uiParam parameter to the new height.

Windows 95: Not supported.
SPI_SETMOUSEHOVERTIME Sets the time, in milliseconds, that the mouse pointer has to stay in the hover rectangle for TrackMouseEvent to generate a WM_MOUSEHOVER message. This is used only if you pass HOVER_DEFAULT in the dwHoverTime parameter in the call to TrackMouseEvent. Set the uiParam parameter to the new time.

Windows 95: Not supported.
SPI_SETMOUSEHOVERWIDTH Sets the width, in pixels, of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message. Set the uiParam parameter to the new width.

Windows 95: Not supported.
SPI_SETMOUSESPEED | Windows 98/Me, Windows 2000 or later: Sets the current mouse speed. The pvParam parameter is an integer between 1 (slowest) and 20 (fastest). A value of 10 is the default. This value is typically set using the mouse control panel application.
SPI_SETMOUSETRAILS Windows 95/98 and Whistler: Enables or disables the Mouse Trails feature, which improves the visibility of mouse cursor movements by briefly showing a trail of cursors and quickly erasing them.

To disable the feature, set the uiParam parameter to zero or 1. To enable the feature, set uiParam to a value greater than 1 to indicate the number of cursors drawn in the trail.

Windows NT/2000 or later: Not supported.

SPI_SETSNAPTODEFBUTTON Enables or disables the snap-to-default-button feature. If enabled, the mouse cursor automatically moves to the default button, such as OK or Apply, of a dialog box. Set the uiParam parameter to TRUE to enable the feature, or FALSE to disable it. Applications should use the ShowWindow function when displaying a dialog box so the dialog manager can position the mouse cursor.

Windows 95: Not supported.
SPI_SETWHEELSCROLLLINES Sets the number of lines to scroll when the mouse wheel is rotated. The number of lines is set from the uiParam parameter.

The number of lines is the suggested number of lines to scroll when the mouse wheel is rolled without using modifier keys. If the number is 0, then no scrolling should occur. If the number of lines to scroll is greater than the number of lines viewable, and in particular if it is WHEEL_PAGESCROLL (#defined as UINT_MAX), the scroll operation should be interpreted as clicking once in the page down or page up regions of the scroll bar.

Windows 95: Not supported.

The following are the menu parameters.
Menu parameter | Meaning
SPI_GETMENUDROPALIGNMENT | Determines whether pop-up menus are left-aligned or right-aligned, relative to the corresponding menu-bar item. The pvParam parameter must point to a BOOL variable that receives TRUE if left-aligned, or FALSE otherwise.
SPI_GETMENUFADE | Windows 2000 and later: Indicates whether menu fade animation is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE when fade animation is enabled and FALSE when it is disabled. If fade animation is disabled, menus use slide animation. This flag is ignored unless menu animation is enabled, which you can do using the SPI_SETMENUANIMATION flag. For more information, see AnimateWindow .
SPI_GETMENUSHOWDELAY Indicates the time, in milliseconds, that the system waits before displaying a shortcut menu when the mouse cursor is over a submenu item. The pvParam parameter must point to a DWORD variable that receives the time of the delay.

Windows 95: Not supported.
SPI_SETMENUDROPALIGNMENT | Sets the alignment value of pop-up menus. The uiParam parameter specifies TRUE for right alignment, or FALSE for left alignment.
SPI_SETMENUFADE | Windows 2000 and later: Enables or disables menu fade animation. Set pvParam to TRUE to enable the menu fade effect or FALSE to disable it. If fade animation is disabled, menus use slide animation. he The menu fade effect is possible only if the system has a color depth of more than 256 colors. This flag is ignored unless SPI_MENUANIMATION is also set. For more information, see AnimateWindow.
SPI_SETMENUSHOWDELAY Set uiParam to the time, in milliseconds, that the system waits before displaying a shortcut menu when the mouse cursor is over a submenu item.

Windows 95: Not supported.

The following are the power parameters.
Power parameter Meaning
SPI_GETLOWPOWERACTIVE Determines whether the low-power phase of screen saving is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE if disabled.

Windows 98/Me: This flag is supported for 16-bit and 32-bit applications.

Windows 95: This flag is supported for 16-bit applications only.

Windows NT/2000 or later: This flag is supported for 32-bit applications on Windows 2000 and later. It is not supported for 16-bit applications.
SPI_GETLOWPOWERTIMEOUT Retrieves the time-out value for the low-power phase of screen saving. The pvParam parameter must point to an integer variable that receives the value.

Windows 98/Me: This flag is supported for 16-bit and 32-bit applications.

Windows 95: This flag is supported for 16-bit applications only.

Windows NT/2000 or later: This flag is supported for 32-bit applications on Windows 2000 and later. It is not supported for 16-bit applications.
SPI_GETPOWEROFFACTIVE Determines whether the power-off phase of screen saving is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE if disabled.

Windows 98/Me: This flag is supported for 16-bit and 32-bit applications.

Windows 95: This flag is supported for 16-bit applications only.

Windows NT/2000 or later: This flag is supported for 32-bit applications on Windows 2000 and later. It is not supported for 16-bit applications.
SPI_GETPOWEROFFTIMEOUT Retrieves the time-out value for the power-off phase of screen saving. The pvParam parameter must point to an integer variable that receives the value.

Windows 98/Me: This flag is supported for 16-bit and 32-bit applications.

Windows 95: This flag is supported for 16-bit applications only.

Windows NT/2000 or later: This flag is supported for 32-bit applications on Windows 2000 and later. It is not supported for 16-bit applications.
SPI_SETLOWPOWERACTIVE Activates or deactivates the low-power phase of screen saving. Set uiParam to 1 to activate, or zero to deactivate. The pvParam parameter must be NULL.

Windows 98/Me: This flag is supported for 16-bit and 32-bit applications.

Windows 95: This flag is supported for 16-bit applications only.

Windows NT/2000 or later: This flag is supported for 32-bit applications on Windows 2000 and later. It is not supported for 16-bit applications.
SPI_SETLOWPOWERTIMEOUT Sets the time-out value, in seconds, for the low-power phase of screen saving. The uiParam parameter specifies the new value. The pvParam parameter must be NULL.

Windows 98/Me: This flag is supported for 16-bit and 32-bit applications.

Windows 95: This flag is supported for 16-bit applications only.

Windows NT/2000 or later: This flag is supported for 32-bit applications on Windows 2000 and later. It is not supported for 16-bit applications.
SPI_SETPOWEROFFACTIVE Activates or deactivates the power-off phase of screen saving. Set uiParam to 1 to activate, or zero to deactivate. The pvParam parameter must be NULL.

Windows 98/Me: This flag is supported for 16-bit and 32-bit applications.

Windows 95: This flag is supported for 16-bit applications only.

Windows NT/2000 or later: This flag is supported for 32-bit applications on Windows 2000 and later. It is not supported for 16-bit applications.
SPI_SETPOWEROFFTIMEOUT Sets the time-out value, in seconds, for the power-off phase of screen saving. The uiParam parameter specifies the new value. The pvParam parameter must be NULL.

Windows 98/Me: This flag is supported for 16-bit and 32-bit applications.

Windows 95: This flag is supported for 16-bit applications only.

Windows NT/2000 or later: This flag is supported for 32-bit applications on Windows 2000 and later. It is not supported for 16-bit applications.

The following are the screen saver parameters.
Screen saver parameter | Meaning
SPI_GETSCREENSAVEACTIVE | Determines whether screen saving is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if screen saving is enabled, or FALSE otherwise.
SPI_GETSCREENSAVERRUNNING | Windows 98/Me, Windows 2000 or later: Determines whether a screen saver is currently running on the window station of the calling process. The pvParam parameter must point to a BOOL variable that receives TRUE if a screen saver is currently running, or FALSE otherwise. Note that only the interactive window station, "WinSta0", can have a screen saver running.
SPI_GETSCREENSAVETIMEOUT | Retrieves the screen saver time-out value, in seconds. The pvParam parameter must point to an integer variable that receives the value.
SPI_SETSCREENSAVEACTIVE | Sets the state of the screen saver. The uiParam parameter specifies TRUE to activate screen saving, or FALSE to deactivate it.
SPI_SETSCREENSAVERRUNNING | Windows 95/98/Me: Used internally; applications should not use this flag.
SPI_SETSCREENSAVETIMEOUT | Sets the screen saver time-out value to the value of the uiParam parameter. This value is the amount of time, in seconds, that the system must be idle before the screen saver activates.

The following are the UI effects parameters. The SPI_SETUIEFFECTS value is used to enable or disable all the UI effect values at once. This table contains the complete list of UI effect values.
UI effects parameter | Meaning
SPI_GETCOMBOBOXANIMATION | Windows 98/Me, Windows 2000 or later: Indicates whether the slide-open effect for combo boxes is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE for enabled, or FALSE for disabled.
SPI_GETCURSORSHADOW | Windows 2000 and later: Indicates whether the cursor has a shadow around it. The pvParam parameter must point to a BOOL variable that receives TRUE if the shadow is enabled, FALSE if it is disabled. This effect appears only if the system has a color depth of more than 256 colors.
SPI_GETGRADIENTCAPTIONS | Windows 98/Me, Windows 2000 or later: Indicates whether the gradient effect for window title bars is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE for enabled, or FALSE for disabled. For more information about the gradient effect, see the GetSysColor function.
SPI_GETHOTTRACKING Windows 98/Me, Windows 2000 or later: Indicates whether hot tracking of user-interface elements, such as menu names on menu bars, is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE for enabled, or FALSE for disabled.

Hot tracking means that when the cursor moves over an item, it is highlighted but not selected. You can query this value to decide whether to use hot tracking in the user interface of your application.

SPI_GETLISTBOXSMOOTHSCROLLING | Windows 98/Me, Windows 2000 or later: Indicates whether the smooth-scrolling effect for list boxes is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE for enabled, or FALSE for disabled.
SPI_GETMENUANIMATION Windows 98/Me, Windows 2000 or later: Indicates whether the menu animation feature is enabled. This master switch must be on to enable menu animation effects. The pvParam parameter must point to a BOOL variable that receives TRUE if animation is enabled and FALSE if it is disabled.

Windows 2000 and later: If animation is enabled, SPI_GETMENUFADE indicates whether menus use fade or slide animation.

SPI_GETMENUUNDERLINES | Windows 98/Me, Windows 2000 or later: Same as SPI_GETKEYBOARDCUES.
SPI_GETSELECTIONFADE Windows 2000 and later: Indicates whether the selection fade effect is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled or FALSE if disabled.

The selection fade effect causes the menu item selected by the user to remain on the screen briefly while fading out after the menu is dismissed.
SPI_GETTOOLTIPANIMATION | Windows 2000 and later: Indicates whether ToolTip animation is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled or FALSE if disabled. If ToolTip animation is enabled, SPI_GETTOOLTIPFADE indicates whether ToolTips use fade or slide animation.
SPI_GETTOOLTIPFADE | Windows 2000 and later: If SPI_SETTOOLTIPANIMATION is enabled, SPI_GETTOOLTIPFADE indicates whether ToolTip animation uses a fade effect or a slide effect. The pvParam parameter must point to a BOOL variable that receives TRUE for fade animation or FALSE for slide animation. For more information on slide and fade effects, see AnimateWindow.
SPI_GETUIEFFECTS | Windows 2000 and later: Indicates whether all UI effects are disabled or not. The pvParam parameter must point to a BOOL variable that receives TRUE if UI effects are enabled, or FALSE if they are disabled. For the complete list of UI effects, see the Remarks section later in this topic.
SPI_SETCOMBOBOXANIMATION | Windows 98/Me, Windows 2000 or later: Enables or disables the slide-open effect for combo boxes. Set the pvParam parameter to TRUE to enable the gradient effect, or FALSE to disable it.
SPI_SETCURSORSHADOW | Windows 2000 and later: Enables or disables a shadow around the cursor. The pvParam parameter is a BOOL variable. Set pvParam to TRUE to enable the shadow or FALSE to disable the shadow. This effect appears only if the system has a color depth of more than 256 colors.
SPI_SETGRADIENTCAPTIONS | Windows 98/Me, Windows 2000 or later: Enables or disables the gradient effect for window title bars. Set the pvParam parameter to TRUE to enable it, or FALSE to disable it. The gradient effect is possible only if the system has a color depth of more than 256 colors. For more information about the gradient effect, see the GetSysColor function.
SPI_SETHOTTRACKING Windows 98/Me, Windows 2000 or later: Enables or disables hot tracking of user-interface elements such as menu names on menu bars. Set the pvParam parameter to TRUE to enable it, or FALSE to disable it.

Hot-tracking means that when the cursor moves over an item, it is highlighted but not selected.
SPI_SETLISTBOXSMOOTHSCROLLING | Windows 98/Me, Windows 2000 or later: Enables or disables the smooth-scrolling effect for list boxes. Set the pvParam parameter to TRUE to enable the smooth-scrolling effect, or FALSE to disable it.
SPI_SETMENUANIMATION Windows 98/Me, Windows 2000 or later: Enables or disables menu animation. This master switch must be on for any menu animation to occur. The pvParam parameter is a BOOL variable; set pvParam to TRUE to enable animation and FALSE to disable animation.

Windows 2000 and later: If animation is enabled, SPI_GETMENUFADE indicates whether menus use fade or slide animation.

SPI_SETMENUUNDERLINES | Windows 98/Me, Windows 2000 or later: Same as SPI_SETKEYBOARDCUES.
SPI_SETSELECTIONFADE Windows 2000 and later: Set pvParam to TRUE to enable the selection fade effect or FALSE to disable it.

The selection fade effect causes the menu item selected by the user to remain on the screen briefly while fading out after the menu is dismissed. The selection fade effect is possible only if the system has a color depth of more than 256 colors.

SPI_SETTOOLTIPANIMATION | Windows 2000 and later: Set pvParam to TRUE to enable ToolTip animation or FALSE to disable it. If enabled, you can use SPI_SETTOOLTIPFADE to specify fade or slide animation.
SPI_SETTOOLTIPFADE | Windows 2000 and later: If the SPI_SETTOOLTIPANIMATION flag is enabled, use SPI_SETTOOLTIPFADE to indicate whether ToolTip animation uses a fade effect or a slide effect. Set pvParam to TRUE for fade animation or FALSE for slide animation. The tooltip fade effect is possible only if the system has a color depth of more than 256 colors. For more information on the slide and fade effects, see the AnimateWindow function.
SPI_SETUIEFFECTS | Windows 2000 and later: Enables or disables UI effects. Set the pvParam parameter to TRUE to enable all UI effects or FALSE to disable all UI effects. For the complete list of UI effects, see the Remarks section later in this topic.

The following are the window parameters.
Window parameter | Meaning
SPI_GETACTIVEWINDOWTRACKING | Windows 98/Me, Windows 2000 or later: Indicates whether active window tracking (activating the window the mouse is on) is on or off. The pvParam parameter must point to a BOOL variable that receives TRUE for on, or FALSE for off.
SPI_GETACTIVEWNDTRKZORDER | Windows 98/Me, Windows 2000 or later: Indicates whether windows activated through active window tracking will be brought to the top. The pvParam parameter must point to a BOOL variable that receives TRUE for on, or FALSE for off.
SPI_GETACTIVEWNDTRKTIMEOUT | Windows 98/Me, Windows 2000 or later: Indicates the active window tracking delay, in milliseconds. The pvParam parameter must point to a DWORD variable that receives the time.
SPI_GETANIMATION | Retrieves the animation effects associated with user actions. The pvParam parameter must point to an ANIMATIONINFO structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(ANIMATIONINFO).
SPI_GETBORDER | Retrieves the border multiplier factor that determines the width of a window's sizing border. The pvParam parameter must point to an integer variable that receives this value.
SPI_GETCARETWIDTH | Windows 2000 or later: Indicates the caret width in edit controls. The pvParam parameter must point to a DWORD that receives the width of the caret in pixels.
SPI_GETDRAGFULLWINDOWS Determines whether dragging of full windows is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE otherwise.

Windows 95: This flag is supported only if Windows Plus! is installed. See SPI_GETWINDOWSEXTENSION.
SPI_GETFOREGROUNDFLASHCOUNT | Windows 98/Me, Windows 2000 or later: Indicates the number of times SetForegroundWindow will flash the taskbar button when rejecting a foreground switch request. The pvParam parameter must point to a DWORD variable that receives the value.
SPI_GETFOREGROUNDLOCKTIMEOUT | Windows 98/Me, Windows 2000 or later: Indicates the amount of time following user input, in milliseconds, during which the system will not allow applications to force themselves into the foreground. The pvParam parameter must point to a DWORD variable that receives the time.
SPI_GETMINIMIZEDMETRICS | Retrieves the metrics associated with minimized windows. The pvParam parameter must point to a MINIMIZEDMETRICS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(MINIMIZEDMETRICS).
SPI_GETNONCLIENTMETRICS | Retrieves the metrics associated with the nonclient area of nonminimized windows. The pvParam parameter must point to a NONCLIENTMETRICS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(NONCLIENTMETRICS).
SPI_GETSHOWIMEUI | Windows 98/Me, Windows 2000 or later: Indicates whether the IME status window is visible (on a per-user basis). The pvParam parameter must point to a BOOL variable that receives TRUE if the status window is visible, or FALSE if it is not.
SPI_SETACTIVEWINDOWTRACKING | Windows 98/Me, Windows 2000 or later: Sets active window tracking (activating the window the mouse is on) either on or off. Set pvParam to TRUE for on or FALSE for off.
SPI_SETACTIVEWNDTRKZORDER | Windows 98/Me, Windows 2000 or later: Indicates whether or not windows activated through active window tracking should be brought to the top. Set pvParam to TRUE for on or FALSE for off.
SPI_SETACTIVEWNDTRKTIMEOUT | Windows 98/Me, Windows 2000 or later: Sets the active window tracking delay. Set pvParam to the number of milliseconds to delay before activating the window under the mouse pointer.
SPI_SETANIMATION | Sets the animation effects associated with user actions. The pvParam parameter must point to an ANIMATIONINFO structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(ANIMATIONINFO).
SPI_SETBORDER | Sets the border multiplier factor that determines the width of a window's sizing border. The uiParam parameter specifies the new value.
SPI_SETCARETWIDTH | Windows 2000 and later: Sets the caret width in edit controls. Set pvParam to the desired width, in pixels. The default and minimum value is 1.
SPI_SETDRAGFULLWINDOWS Sets dragging of full windows either on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.

Windows 95: This flag is supported only if Windows Plus! is installed. See SPI_GETWINDOWSEXTENSION.
SPI_SETDRAGHEIGHT | Sets the height, in pixels, of the rectangle used to detect the start of a drag operation. Set uiParam to the new value. To retrieve the drag height, call GetSystemMetrics with the SM_CYDRAG flag.
SPI_SETDRAGWIDTH | Sets the width, in pixels, of the rectangle used to detect the start of a drag operation. Set uiParam to the new value. To retrieve the drag width, call GetSystemMetrics with the SM_CXDRAG flag.
SPI_SETFOREGROUNDFLASHCOUNT | Windows 98/Me, Windows 2000 or later: Sets the number of times SetForegroundWindow will flash the taskbar button when rejecting a foreground switch request. Set pvParam to the number of times to flash.
SPI_SETFOREGROUNDLOCKTIMEOUT | Windows 98/Me, Windows 2000 or later: Sets the amount of time following user input, in milliseconds, during which the system will not allow applications to force themselves into the foreground. Set pvParam to the new timeout value.
SPI_SETMINIMIZEDMETRICS | Sets the metrics associated with minimized windows. The pvParam parameter must point to a MINIMIZEDMETRICS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(MINIMIZEDMETRICS).
SPI_SETNONCLIENTMETRICS | Sets the metrics associated with the nonclient area of nonminimized windows. The pvParam parameter must point to a NONCLIENTMETRICS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(NONCLIENTMETRICS).
SPI_SETSHOWIMEUI | Windows 98/Me, Windows 2000 or later: Sets whether the IME status window is visible or not on a per-user basis. The uiParam parameter specifies TRUE for on or FALSE for off.

The following parameters are specific to Windows 95, Windows 98, and Windows Me.
Parameter | Meaning
SPI_GETWINDOWSEXTENSION | Windows 95: Indicates whether the Windows extension, Windows Plus!, is installed. Set the uiParam parameter to 1. The pvParam parameter is not used. The function returns TRUE if the extension is installed, or FALSE if it is not.
SPI_SETPENWINDOWS | Windows 95/98/Me: Specifies that pen windows is being loaded or unloaded. The uiParam parameter is TRUE when loading and FALSE when unloading pen windows. The pvParam parameter is NULL.

uiParam
[in] Depends on the system parameter being queried or set. For more information about system-wide parameters, see the uiAction parameter. If not otherwise indicated, you must specify zero for this parameter.
pvParam
[in/out] Depends on the system parameter being queried or set. For more information about system-wide parameters, see the uiAction parameter. If not otherwise indicated, you must specify NULL for this parameter.
fWinIni
[in] If a system parameter is being set, specifies whether the user profile is to be updated, and if so, whether the WM_SETTINGCHANGE message is to be broadcast to all top-level windows to notify them of the change.

This parameter can be zero if you don't want to update the user profile or broadcast the WM_SETTINGCHANGE message, or it can be one or more of the following values.
Value | Action
SPIF_UPDATEINIFILE | Writes the new system-wide parameter setting to the user profile.
SPIF_SENDCHANGE | Broadcasts the WM_SETTINGCHANGE message after updating the user profile.
SPIF_SENDWININICHANGE | Same as SPIF_SENDCHANGE.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Remarks

This function is intended for use with applications that allow the user to customize the environment.

A keyboard layout name should be derived from the hexadecimal value of the language identifier corresponding to the layout. For example, U.S. English has a language identifier of 0x0409, so the primary U.S. English layout is named "00000409." Variants of U.S. English layout, such as the Dvorak layout, are named "00010409," "00020409" and so on. For a list of the primary language identifiers and sublanguage identifiers that make up a language identifier, see the MAKELANGID macro.

Windows Me and Whistler: During the time that the primary button is held down to activate the Mouse ClickLock feature, the user can move the mouse. Once the primary button is locked down, releasing the primary button does not result in a WM_LBUTTONUP message. Thus, it will appear to an application that the primary button is still down. Any subsequent button message releases the primary button, sending a WM_LBUTTONUP message to the application, thus the button can be unlocked programmatically or through the user clicking any button.

For an example, see Getting Hardware Information.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Information Overview, System Information Functions, ACCESSTIMEOUT, ANIMATIONINFO, FILTERKEYS, HIGHCONTRAST, ICONMETRICS, LOGFONT, MAKELANGID, MINIMIZEDMETRICS, MOUSEKEYS, NONCLIENTMETRICS, RECT, SERIALKEYS, SOUNDSENTRY, STICKYKEYS, TOGGLEKEYS, WM_SETTINGCHANGE


TranslateName

The TranslateName function converts a directory service object name from one format to another.

BOOLEAN TranslateName (
  LPCTSTR lpAccountName,                  // object name
  EXTENDED_NAME_FORMAT AccountNameFormat, // name format
  EXTENDED_NAME_FORMAT DesiredNameFormat, // new name format
  LPTSTR lpTranslatedName,                // name buffer
  PULONG nSize                            // buffer size
);

Parameters

lpAccountName
[in] Pointer to a null-terminated string containing the name to translate.
AccountNameFormat
[in] Value from the EXTENDED_NAME_FORMAT enumeration type indicating the format of the lpAccountName name.
DesiredNameFormat
[in] Value from the EXTENDED_NAME_FORMAT enumeration type indicating the desired format of the converted name. This value cannot be NameUnknown.
lpTranslatedName
[out] Pointer to a buffer that receives the name in the converted format.
nSize
[in/out] Pointer to a variable. On input, the variable indicates the size, in TCHARs, of the lpTranslatedName buffer. On output, the variable returns the size of the returned string including the terminating null character.

If the lpTranslatedName buffer is too small to hold the converted name, the function fails and nSize receives the required buffer size.

Return Values

If the function succeeds, the return value is a nonzero value.

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

Remarks

TranslateName fails if it cannot bind to Active Directory on a Windows 2000 domain controller.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Secext.h; include Security.h.
Library: Use Secur32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

System Information Overview, System Information Functions, DsCrackNames, EXTENDED_NAME_FORMAT


VerifyVersionInfo

The VerifyVersionInfo function compares a set of operating system version requirements to the corresponding values for the currently running version of the system.

BOOL VerifyVersionInfo(
  LPOSVERSIONINFOEX lpVersionInfo,  // version info
  DWORD dwTypeMask,                 // attributes
  DWORDLONG dwlConditionMask        // comparison type
);

Parameters

lpVersionInfo
[in] Pointer to an OSVERSIONINFOEX structure containing the operating system version requirements to compare. The dwTypeMask parameter indicates the members of this structure that contain information to compare.

You must set the dwOSVersionInfoSize member of this structure to sizeof(OSVERSIONINFOEX). You must also specify valid data for the members indicated by dwTypeMask. The function ignores structure members for which the corresponding dwTypeMask bit is not set.

dwTypeMask
[in] Specifies the members of the OSVERSIONINFOEX structure to test. This parameter can be one or more of the following values.
Value | Corresponding member
VER_BUILDNUMBER | dwBuildNumber
VER_MAJORVERSION | dwMajorVersion
VER_MINORVERSION | dwMinorVersion
VER_PLATFORMID | dwPlatformId
VER_SERVICEPACKMAJOR | wServicePackMajor
VER_SERVICEPACKMINOR | wServicePackMinor
VER_SUITENAME | wSuiteMask
VER_PRODUCT_TYPE | wProductType

dwlConditionMask
[in] A 64-bit value that indicates the type of comparison to use for each lpVersionInfo member being compared. To build this value, call the VerSetConditionMask function or the VER_SET_CONDITION macro once for each OSVERSIONINFOEX member being compared.

Return Values

If the currently running operating system satisfies the specified requirements, the return value is a nonzero value.

If the current system does not satisfy the requirements, the return value is zero and GetLastError returns ERROR_OLD_WIN_VERSION.

If the function fails, the return value is zero and GetLastError returns an error code other than ERROR_OLD_WIN_VERSION.

Remarks

The VerifyVersionInfo function retrieves version information about the currently running operating system and compares it to the valid members of the lpVersionInfo structure. This enables you to easily determine the presence of a required set of operating system version conditions. It is preferable to use VerifyVersionInfo rather than calling the GetVersionEx function to perform your own comparisons.

Typically, VerifyVersionInfo returns a nonzero value only if all specified tests succeed. However, major, minor, and service pack versions are tested in a hierarchical manner because the operating system version is a combination of these values. If a condition exists for the major version, it supersedes the conditions specified for minor version and service pack version. (You cannot test for major version greater than 5 and minor version less than or equal to 1. If you specify such a test, the function will change the request to test for a minor version greater than 1 because it is performing a greater than operation on the major version.)

The function tests these values in this order: major version, minor version, and service pack version. The function continues testing values while they are equal, and stops when one of the values does not meet the specified condition. For example, if you test for a system greater than or equal to version 5.1 service pack 1, the test succeeds if the current version is 6.0. (The major version is greater than the specified version, so the testing stops.) In the same way, if you test for a system greater than or equal to version 5.1 service pack 1, the test succeeds if the current version is 5.2. (The minor version is greater than the specified versions, so the testing stops.) However, if you test for a system greater than or equal to version 5.1 service pack 1, the test fails if the current version is 5.0 service pack 2. (The minor version is not greater than the specified version, so the testing stops.)

To verify a range of system versions, you must call VerifyVersionInfo twice. For example, to verify that the system version is greater than 5.0 but less than or equal to 5.1, first call VerifyVersionInfo to test that the major version is 5 and the minor version is greater than 0, then call VerifyVersionInfo again to test that the major version is 5 and the minor version is less than or equal to 1.

Identifying the current operating system is usually not the best way to determine whether a particular operating system feature is present. This is because the operating system may have had new features added in a redistributable DLL. Rather than using GetVersionEx to determine the operating system platform or version number, test for the presence of the feature itself. For more information, see Operating System Version.

For an example, see Verifying the System Version.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

System Information Overview, System Information Functions, GetVersionEx, OSVERSIONINFOEX, VER_SET_CONDITION, VerSetConditionMask


VerSetConditionMask

The VerSetConditionMask function sets the bits of a 64-bit value to indicate the comparison operator to use for a specified operating system version attribute. This function is used to build the dwlConditionMask parameter of the VerifyVersionInfo function.

ULONGLONG VerSetConditionMask(
  ULONGLONG dwlConditionMask,  // mask whose bits are set
  DWORD dwTypeBitMask,         // type of attribute
  BYTE dwConditionMask         // type of comparison
);

Parameters

dwlConditionMask
A 64-bit variable to be passed as the dwlConditionMask parameter of the VerifyVersionInfo function. The function stores the comparison information in the bits of this variable.

Before the first call to VerSetCondition, initialize this variable to zero. For subsequent calls, pass in the variable used in the previous call.

dwTypeBitMask
Indicates the OSVERSIONINFOEX member whose comparison type is being set. This value corresponds to one of the bits specified in the dwTypeMask parameter for the VerifyVersionInfo function. This parameter can be one of the following values.
Value | Corresponding member
VER_BUILDNUMBER | dwBuildNumber
VER_MAJORVERSION | dwMajorVersion
VER_MINORVERSION | dwMinorVersion
VER_PLATFORMID | dwPlatformId
VER_SERVICEPACKMAJOR | wServicePackMajor
VER_SERVICEPACKMINOR | wServicePackMinor
VER_SUITENAME | wSuiteMask
VER_PRODUCT_TYPE | wProductType

dwConditionMask
Indicates the comparison operator to use for the operating system version attribute specified by the dwTypeBitMask parameter. The VerifyVersionInfo function uses this operator to compare a specified attribute value to the corresponding value for the currently running system.

For all values of dwTypeBitMask other than VER_SUITENAME, this parameter can be one of the following values.
Value | Meaning
VER_EQUAL | The current value must be equal to the specified value.
VER_GREATER | The current value must be greater than the specified value.
VER_GREATER_EQUAL | The current value must be greater than or equal to the specified value.
VER_LESS | The current value must be less than the specified value.
VER_LESS_EQUAL | The current value must be less than or equal to the specified value.

If dwTypeBitMask is VER_SUITENAME, this parameter can be one of the following values.
Value | Meaning
VER_AND | All product suites specified in the wSuiteMask member must be present in the current system.
VER_OR | At least one of the specified product suites must be present in the current system.

Return Value

The function returns the condition mask value.

Remarks

Call this function once for each bit set in the dwTypeMask parameter of the VerifyVersionInfo function.

Examples

For an example, see Verifying the System Version.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnt.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

System Information Overview, System Information Functions, OSVERSIONINFOEX, VerifyVersionInfo


System Information Structures

The following structures are used to retrieve or set system information.

ANIMATIONINFO
HW_PROFILE_INFO
MINIMIZEDMETRICS
NONCLIENTMETRICS
OSVERSIONINFO
OSVERSIONINFOEX
SYSTEM_INFO


ANIMATIONINFO

The ANIMATIONINFO structure specifies the animation effects associated with user actions. This structure is used with the SystemParametersInfo function when the SPI_GETANIMATION or SPI_SETANIMATION action value is specified.

typedef struct tagANIMATIONINFO {
  UINT cbSize;
  int  iMinAnimate;
} ANIMATIONINFO, *LPANIMATIONINFO;

Members

cbSize
Specifies the size of the structure, in bytes.
iMinAnimate
Indicates that minimize and restore animation is enabled (if the member is a nonzero value) or not enabled (if zero).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

System Information Overview, System Information Structures, SystemParametersInfo


HW_PROFILE_INFO

The HW_PROFILE_INFO structure contains information about a hardware profile. The GetCurrentHwProfile function uses this structure to retrieve the current hardware profile for the local computer.

typedef struct tagHW_PROFILE_INFO {
  DWORD           dwDockInfo;
  TCHAR           szHwProfileGuid[HW_PROFILE_GUIDLEN];
  TCHAR           szHwProfileName[MAX_PROFILE_LEN];
} HW_PROFILE_INFO, *LPHW_PROFILE_INFO;

Members

dwDockInfo
A set of bit flags that indicate the docking state of the computer. This member can be a combination of the following values.
Value | Meaning
DOCKINFO_DOCKED | The computer is docked. This flag is always set for desktop systems that cannot be undocked.
DOCKINFO_UNDOCKED | The computer is undocked. This flag is always set for desktop systems that cannot be undocked.
DOCKINFO_USER_SUPPLIED If this flag is set, GetCurrentHwProfile retrieved the current docking state from information provided by the user in the Hardware Profiles page of the System control panel application.

Currently, Windows NT/Windows 2000 and Windows 95 are not able to detect the docking state. Consequently, this flag is always set.

DOCKINFO_USER_DOCKED | The computer is docked, according to information provided by the user. This value is a combination of the DOCKINFO_USER_SUPPLIED and DOCKINFO_DOCKED flags.
DOCKINFO_USER_UNDOCKED | The computer is undocked, according to information provided by the user. This value is a combination of the DOCKINFO_USER_SUPPLIED and DOCKINFO_UNDOCKED flags.

szHwProfileGuid
A null-terminated string that contains the globally unique identifier (GUID) string for the current hardware profile. The string returned by GetCurrentHwProfile encloses the GUID in curly braces "{}" and includes a null-terminator; for example:
"{12340001-4980-1920-6788-123456789012}"

You can use this string as a registry subkey under your application's configuration settings key in HKEY_CURRENT_USER. This enables you to store settings for each hardware profile.

szHwProfileName
A null-terminated string that contains the display name for the current hardware profile.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 OSR2 or later.
Header: Declared in Winbase.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

System Information Overview, System Information Structures, GetCurrentHwProfile


MINIMIZEDMETRICS

The MINIMIZEDMETRICS structure contains the scalable metrics associated with minimized windows. This structure is used with the SystemParametersInfo function when the SPI_GETMINIMIZEDMETRICS or SPI_SETMINIMIZEDMETRICS action value is specified.

typedef struct tagMINIMIZEDMETRICS {
  UINT    cbSize;
  int     iWidth;
  int     iHorzGap;
  int     iVertGap;
  int     iArrange;
}   MINIMIZEDMETRICS, *LPMINIMIZEDMETRICS;

Members

cbSize
Specifies the size of the structure, in bytes.
iWidth
Specifies the width, in pixels, of minimized windows.
iHorzGap
Specifies the amount of horizontal space, in pixels, between arranged minimized windows.
iVertGap
Specifies the amount of vertical space, in pixels, between arranged minimized windows.
iArrange
Specifies the starting position and direction used when arranging minimized windows. The starting position must be one of the following values.
Value | Meaning
ARW_BOTTOMLEFT | Start at the lower-left corner of the work area.
ARW_BOTTOMRIGHT | Start at the lower-right corner of the work area.
ARW_TOPLEFT | Start at the upper-left corner of the work area.
ARW_TOPRIGHT | Start at the upper-right corner of the work area.

The direction must be one of the following values.
Value | Meaning
ARW_LEFT | Arrange left (valid with ARW_BOTTOMRIGHT and ARW_TOPRIGHT only).
ARW_RIGHT | Arrange right (valid with ARW_BOTTOMLEFT and ARW_TOPLEFT only).
ARW_UP | Arrange up (valid with ARW_BOTTOMLEFT and ARW_BOTTOMRIGHT only).
ARW_DOWN | Arrange down (valid with ARW_TOPLEFT and ARW_TOPRIGHT only).

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

System Information Overview, System Information Structures, SystemParametersInfo


NONCLIENTMETRICS

The NONCLIENTMETRICS structure contains the scalable metrics associated with the nonclient area of a nonminimized window. This structure is used by the SPI_GETNONCLIENTMETRICS and SPI_SETNONCLIENTMETRICS actions of SystemParametersInfo.

typedef struct tagNONCLIENTMETRICS {
  UINT    cbSize;
  int     iBorderWidth;
  int     iScrollWidth;
  int     iScrollHeight;
  int     iCaptionWidth;
  int     iCaptionHeight;
  LOGFONT lfCaptionFont;
  int     iSmCaptionWidth;
  int     iSmCaptionHeight;
  LOGFONT lfSmCaptionFont;
  int     iMenuWidth;
  int     iMenuHeight;
  LOGFONT lfMenuFont;
  LOGFONT lfStatusFont;
  LOGFONT lfMessageFont;
} NONCLIENTMETRICS, *LPNONCLIENTMETRICS;

Members

cbSize
Specifies the size of the structure, in bytes.
iBorderWidth
Specifies the thickness, in pixels, of the sizing border.
iScrollWidth
Specifies the width, in pixels, of a standard vertical scroll bar.
iScrollHeight
Specifies the height, in pixels, of a standard horizontal scroll bar.
iCaptionWidth
Specifies the width, in pixels, of caption buttons.
iCaptionHeight
Specifies the height, in pixels, of caption buttons.
lfCaptionFont
Contains information about the caption font.
iSmCaptionWidth
Specifies the width, in pixels, of small caption buttons.
iSmCaptionHeight
Specifies the height, in pixels, of small captions.
lfSmCaptionFont
Contains information about the small caption font.
iMenuWidth
Specifies the width, in pixels, of menu-bar buttons.
iMenuHeight
Specifies the height, in pixels, of a menu bar.
lfMenuFont
Contains information about the font used in menu bars.
lfStatusFont
Contains information about the font used in status bars and tooltips.
lfMessageFont
Contains information about the font used in message boxes.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

System Information Overview, System Information Structures, SystemParametersInfo


OSVERSIONINFO

The OSVERSIONINFO data structure contains operating system version information. The information includes major and minor version numbers, a build number, a platform identifier, and descriptive text about the operating system. This structure is used with the GetVersionEx function.

typedef struct _OSVERSIONINFO{
  DWORD dwOSVersionInfoSize;
  DWORD dwMajorVersion;
  DWORD dwMinorVersion;
  DWORD dwBuildNumber;
  DWORD dwPlatformId;
  TCHAR szCSDVersion[ 128 ];
} OSVERSIONINFO;

Members

dwOSVersionInfoSize
Specifies the size, in bytes, of this data structure. Set this member to sizeof(OSVERSIONINFO) before calling the GetVersionEx function.
dwMajorVersion
Identifies the major version number of the operating system as follows.
Operating System | Value
Windows 95 | 4
Windows 98 | 4
Windows Me | 4
Windows NT 3.51 | 3
Windows NT 4.0 | 4
Windows 2000 | 5
Whistler | 5

dwMinorVersion
Identifies the minor version number of the operating system as follows.
Operating System | Value
Windows 95 | 0
Windows 98 | 10
Windows Me | 90
Windows NT 3.51 | 51
Windows NT 4.0 | 0
Windows 2000 | 0
Whistler | 1

dwBuildNumber
Windows NT/2000: Identifies the build number of the operating system.

Windows 95/98: Identifies the build number of the operating system in the low-order word. The high-order word contains the major and minor version numbers.

dwPlatformId
Identifies the operating system platform. This member can be one of the following values.
Value | Platform
VER_PLATFORM_WIN32s | Win32s on Windows 3.1.
VER_PLATFORM_WIN32_WINDOWS | Windows 95, Windows 98, or Windows Me.
VER_PLATFORM_WIN32_NT | Windows NT 3.51, Windows NT 4.0, Windows 2000, or Whistler.

szCSDVersion
Windows NT/2000, Whistler: Contains a null-terminated string, such as "Service Pack 3", that indicates the latest Service Pack installed on the system. If no Service Pack has been installed, the string is empty.

Windows 95/98/Me: Contains a null-terminated string that indicates additional version information. For example, " C" indicates Windows 95 OSR2 and " A" indicates Windows 98 SE.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winnt.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

System Information Overview, System Information Structures, GetVersionEx, OSVERSIONINFOEX


OSVERSIONINFOEX

The OSVERSIONINFOEX structure contains operating system version information. The information includes major and minor version numbers, a build number, a platform identifier, and information about product suites and the latest Service Pack installed on the system. This structure is used with the GetVersionEx and VerifyVersionInfo functions.

typedef struct _OSVERSIONINFOEX {
  DWORD dwOSVersionInfoSize;
  DWORD dwMajorVersion;
  DWORD dwMinorVersion;
  DWORD dwBuildNumber;
  DWORD dwPlatformId;
  TCHAR szCSDVersion[ 128 ];
  WORD wServicePackMajor;
  WORD wServicePackMinor;
  WORD wSuiteMask;
  BYTE wProductType;
  BYTE wReserved;
} OSVERSIONINFOEX, *POSVERSIONINFOEX, *LPOSVERSIONINFOEX;

Members

dwOSVersionInfoSize
Specifies the size, in bytes, of this data structure. Set this member to sizeof(OSVERSIONINFOEX) before calling the GetVersionEx or VerifyVersionInfo function.
dwMajorVersion
Identifies the major version number of the operating system as follows.
Operating System | Value
Windows 95 | 4
Windows 98 | 4
Windows Me | 4
Windows NT 3.51 | 3
Windows NT 4.0 | 4
Windows 2000 | 5
Whistler | 5

dwMinorVersion
Identifies the minor version number of the operating system as follows.
Operating System | Value
Windows 95 | 0
Windows 98 | 10
Windows Me | 90
Windows NT 3.51 | 51
Windows NT 4.0 | 0
Windows 2000 | 0
Whistler | 1

dwBuildNumber
Identifies the build number of the operating system.
dwPlatformId
Identifies the operating system platform. This member can be VER_PLATFORM_WIN32_NT.
szCSDVersion
Contains a null-terminated string, such as "Service Pack 3", that indicates the latest Service Pack installed on the system. If no Service Pack has been installed, the string is empty.
wServicePackMajor
Identifies the major version number of the latest Service Pack installed on the system. For example, for Service Pack 3, the major version number is 3. If no Service Pack has been installed, the value is zero.
wServicePackMinor
Identifies the minor version number of the latest Service Pack installed on the system. For example, for Service Pack 3, the minor version number is 0.
wSuiteMask
A set of bit flags that identify the product suites available on the system. This member can be a combination of the following values.
Value | Meaning
VER_SUITE_BACKOFFICE | Microsoft BackOffice components are installed.
VER_SUITE_DATACENTER | Windows 2000 DataCenter Server is installed.
VER_SUITE_ENTERPRISE | Windows 2000 Advanced Server is installed.
VER_SUITE_SMALLBUSINESS | Microsoft Small Business Server is installed.
VER_SUITE_SMALLBUSINESS_RESTRICTED | Microsoft Small Business Server is installed with the restrictive client license in force.
VER_SUITE_TERMINAL | Terminal Services is installed.
VER_SUITE_PERSONAL | Whistler: Whistler Personal is installed.

wProductType
Indicates additional information about the system. This member can be one of the following values.
Value | Meaning
VER_NT_WORKSTATION | Windows 2000 Professional
VER_NT_DOMAIN_CONTROLLER | Windows 2000 domain controller
VER_NT_SERVER | Windows 2000 Server

wReserved
Reserved for future use.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 SP6 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnt.h; include Windows.h.
Unicode: Declared as Unicode and ANSI structures.

See Also

System Information Overview, System Information Structures, GetVersionEx, OSVERSIONINFO, VerifyVersionInfo


SYSTEM_INFO

The SYSTEM_INFO structure contains information about the current computer system. This includes the architecture and type of the processor, the number of processors in the system, the page size, and other such information.

typedef struct _SYSTEM_INFO {
  union {
    DWORD  dwOemId;
    struct {
      WORD wProcessorArchitecture;
      WORD wReserved;
    };
  };
  DWORD  dwPageSize;
  LPVOID lpMinimumApplicationAddress;
  LPVOID lpMaximumApplicationAddress;
  DWORD_PTR dwActiveProcessorMask;
  DWORD dwNumberOfProcessors;
  DWORD dwProcessorType;
  DWORD dwAllocationGranularity;
  WORD wProcessorLevel;
  WORD wProcessorRevision;
} SYSTEM_INFO;

Members

dwOemId
An obsolete member that is retained for compatibility with Windows NT 3.5 and earlier. New applications should use the wProcessorArchitecture branch of the union.

Windows 95/98/Me: The system always sets this member to zero, the value defined for PROCESSOR_ARCHITECTURE_INTEL.

wProcessorArchitecture
Specifies the system's processor architecture. This value can be one of the following values:

PROCESSOR_ARCHITECTURE_UNKNOWN
PROCESSOR_ARCHITECTURE_INTEL
Windows NT 3.51: PROCESSOR_ARCHITECTURE_MIPS
Windows NT 4.0 and earlier: PROCESSOR_ARCHITECTURE_ALPHA
Windows NT 4.0 and earlier: PROCESSOR_ARCHITECTURE_PPC
Whistler 64-bit: PROCESSOR_ARCHITECTURE_IA64
Whistler 64-bit: PROCESSOR_ARCHITECTURE_AMD64

wReserved
Reserved for future use.
dwPageSize
Specifies the page size and the granularity of page protection and commitment. This is the page size used by the VirtualAlloc function.
lpMinimumApplicationAddress
Pointer to the lowest memory address accessible to applications and dynamic-link libraries (DLLs).
lpMaximumApplicationAddress
Pointer to the highest memory address accessible to applications and DLLs.
dwActiveProcessorMask
Specifies a mask representing the set of processors configured into the system. Bit 0 is processor 0; bit 31 is processor 31.
dwNumberOfProcessors
Specifies the number of processors in the system.
dwProcessorType
An obsolete member that is retained for compatibility with Windows NT 3.5 and earlier. Use the wProcessorArchitecture, wProcessorLevel, and wProcessorRevision members to determine the type of processor.

Windows 95/98/Me: Specifies the type of processor in the system. This member is one of the following values:

PROCESSOR_INTEL_386
PROCESSOR_INTEL_486
PROCESSOR_INTEL_PENTIUM

dwAllocationGranularity
Specifies the granularity with which virtual memory is allocated. For example, a VirtualAlloc request to allocate 1 byte will reserve an address space of dwAllocationGranularity bytes. This value was hard coded as 64K in the past, but other hardware architectures may require different values.
wProcessorLevel
Windows NT/2000 or later: Specifies the system's architecture-dependent processor level.

If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_INTEL, wProcessorLevel can be one of the following values.
Value | Meaning
3 | Intel 80386
4 | Intel 80486
5 | Intel Pentium
6 | Intel Pentium Pro or Pentium II

If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_IA64, wProcessorLevel is set to 1.

If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_MIPS, wProcessorLevel is of the form 00xx, where xx is an 8-bit implementation number (bits 8-15 of the PRId register). The member can be the following value.
Value | Meaning
0004 | MIPS R4000

If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_ALPHA, wProcessorLevel is of the form xxxx, where xxxx is a 16-bit processor version number (the low-order 16 bits of a version number from the firmware). The member can be one of the following values.
Value | Meaning
21064 | Alpha 21064
21066 | Alpha 21066
21164 | Alpha 21164

If wProcessorArchitecture is PROCESSOR_ARCHITECTURE_PPC, wProcessorLevel is of the form xxxx, where xxxx is a 16-bit processor version number (the high-order 16 bits of the Processor Version Register). The member can be one of the following values.
Value | Meaning
1 | PPC 601
3 | PPC 603
4 | PPC 604
6 | PPC 603+
9 | PPC 604+
20 | PPC 620

wProcessorRevision
Windows NT/2000 or later: Specifies an architecture-dependent processor revision. The following table shows how the revision value is assembled for each type of processor architecture.
Processor | Value
Intel 80386 or 80486 A value of the form xxyz.

If xx is equal to 0xFF, y - 0xA is the model number, and z is the stepping identifier. For example, an Intel 80486-D0 system returns 0xFFD0.

If xx is not equal to 0xFF, xx + 'A' is the stepping letter and yz is the minor stepping.

Intel Pentium, Cyrix, or NextGen 586 A value of the form xxyy, where xx is the model number and yy is the stepping. Display this value of 0x0201 as follows:

Model xx, Stepping yy
MIPS | A value of the form 00xx, where xx is the 8-bit revision number of the processor (the low-order 8 bits of the PRId register).
ALPHA A value of the form xxyy, where xxyy is the low-order 16 bits of the processor revision number from the firmware. Display this value as follows:

Model A+xx, Pass yy
PPC A value of the form xxyy, where xxyy is the low-order 16 bits of the processor version register. Display this value as follows:

xx.yy

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

System Information Overview, System Information Structures, GetSystemInfo, MapViewOfFile, MapViewOfFileEx


System Information Messages

The following messages are used when setting system information.

WM_SETTINGCHANGE
WM_WININICHANGE


WM_SETTINGCHANGE

The system sends the WM_SETTINGCHANGE message to all top-level windows when the SystemParametersInfo function changes a system-wide setting or when policy settings have changed.

Applications should send WM_SETTINGCHANGE to all top-level windows when they make changes to system parameters. (This message cannot be sent directly to a window.) To send the WM_SETTINGCHANGE message to all top-level windows, use the SendMessageTimeout function with the hwnd parameter set to HWND_BROADCAST.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_SETTINGCHANGE
  WPARAM wParam,   // system parameter indicator
  LPARAM lParam    // system parameter area (LPCTSTR)
);

Parameters

wParam
When the system sends this message as a result of a SystemParametersInfo call, wParam is a flag that indicates the system parameter that was changed. For a list of values, see SystemParametersInfo.

When the system sends this message as a result of a change in policy settings, this parameter indicates the type of policy that was applied. This value is 1 if computer policy was applied or zero if user policy was applied.

When the system sends this message as a result of a change in locale settings, this parameter is zero.

When an application sends this message, this parameter must be NULL.

lParam
When the system sends this message as a result of a SystemParametersInfo call, lParam is a pointer to a string that indicates the area containing the system parameter that was changed. For example, this string can be the name of a registry key or the name of a section in the Win.ini file. This parameter is not particularly useful in determining which system parameter changed. For example, when the string is a registry name, it typically indicates only the leaf node in the registry, not the whole path. In addition, some applications send this message with lParam set to NULL. In general, when you receive this message, you should check and reload any system parameter settings that are used by your application.

When the system sends this message as a result of a change in policy settings, this parameter points to the string "Policy".

When the system sends this message as a result of a change in locale settings, this parameter points to the string "intl".

Return Values

If you process this message, return zero.

Requirements

Windows NT/2000 or later: Requires Windows NT 4.0 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

System Information Overview, System Information Messages, Policy Events, SendMessageTimeout, SystemParametersInfo


WM_WININICHANGE

An application sends the WM_WININICHANGE message to all top-level windows after making a change to the WIN.INI file. The SystemParametersInfo function sends this message after an application uses the function to change a setting in WIN.INI.

Note The WM_WININICHANGE message is provided only for compatibility with earlier versions of the system. Applications should use the WM_SETTINGCHANGE message.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_WININICHANGE
  WPARAM wParam,   // not used; must be zero
  LPARAM lParam    // system parameter area (LPCTSTR)
);

Parameters

wParam
This parameter is not used.
lParam
Pointer to a string containing the name of the system parameter that was changed. For example, this string can be the name of a registry key or the name of a section in the Win.ini file. This parameter is not particularly useful in determining which system parameter changed. For example, when the string is a registry name, it typically indicates only the leaf node in the registry, not the whole path. In addition, some applications send this message with lParam set to NULL. In general, when you receive this message, you should check and reload any system parameter settings that are used by your application.

Return Values

If you process this message, return zero.

Remarks

To send the WM_WININICHANGE message to all top-level windows, use the SendMessage function with the hWnd parameter set to HWND_BROADCAST.

Calls to functions that change WIN.INI may be mapped to the registry instead. This mapping occurs when WIN.INI and the section being changed are specified in the registry under the following keys:

HKEY_LOCAL_MACHINE\Software\Microsoft\
Windows NT\CurrentVersion\IniFileMapping

The change in the storage location has no effect on the behavior of this message.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

System Information Overview, System Information Messages, SystemParametersInfo


System Information Macros

The following macro is used to retrieve or set system information.

VER_SET_CONDITION


VER_SET_CONDITION

The VER_SET_CONDITION macro sets the bits of a 64-bit value to indicate the comparison operator to use for a specified operating system version attribute. This macro is used to build the dwlConditionMask parameter of the VerifyVersionInfo function.

ULONGLONG VER_SET_CONDITION(
  ULONGLONG dwlConditionMask,  // mask whose bits are set
  DWORD dwTypeBitMask,         // type of attribute
  BYTE dwConditionMask         // type of comparison
);

Parameters

dwlConditionMask
A 64-bit variable to be passed as the dwlConditionMask parameter of the VerifyVersionInfo function. The macro stores the comparison information in the bits of this variable.

Before the first call to VER_SET_CONDITION, initialize this variable to zero. For subsequent calls to VER_SET_CONDITION, pass in the variable used in the previous call.

dwTypeBitMask
Indicates the OSVERSIONINFOEX member whose comparison type is being set. This value corresponds to one of the bits specified in the dwTypeMask parameter for the VerifyVersionInfo function. This parameter can be one of the following values.
Value | Corresponding member
VER_BUILDNUMBER | dwBuildNumber
VER_MAJORVERSION | dwMajorVersion
VER_MINORVERSION | dwMinorVersion
VER_PLATFORMID | dwPlatformId
VER_SERVICEPACKMAJOR | wServicePackMajor
VER_SERVICEPACKMINOR | wServicePackMinor
VER_SUITENAME | wSuiteMask
VER_PRODUCT_TYPE | wProductType

dwConditionMask
Indicates the comparison operator to use for the operating system version attribute specified by the dwTypeBitMask parameter. The VerifyVersionInfo function uses this operator to compare a specified attribute value to the corresponding value for the currently running system.

For all values of dwTypeBitMask other than VER_SUITENAME, this parameter can be one of the following values.
Value | Meaning
VER_EQUAL | The current value must be equal to the specified value.
VER_GREATER | The current value must be greater than the specified value.
VER_GREATER_EQUAL | The current value must be greater than or equal to the specified value.
VER_LESS | The current value must be less than the specified value.
VER_LESS_EQUAL | The current value must be less than or equal to the specified value.

If dwTypeBitMask is VER_SUITENAME, this parameter can be one of the following values.
Value | Meaning
VER_AND | All product suites specified in the wSuiteMask member must be present in the current system.
VER_OR | At least one of the specified product suites must be present in the current system.

Return Value

The macro returns the condition mask value.

Remarks

Call this macro once for each bit set in the dwTypeMask parameter of the VerifyVersionInfo function. For examples, see Verifying the System Version.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winnt.h; include Windows.h.

See Also

System Information Overview, System Information Macros, OSVERSIONINFOEX, VerifyVersionInfo


System Information Enumeration Types

The following enumeration types are used to retrieve or set system information.

COMPUTER_NAME_FORMAT
EXTENDED_NAME_FORMAT


COMPUTER_NAME_FORMAT

The COMPUTER_NAME_FORMAT enumeration type contains values that specify a type of computer name.

typedef enum _COMPUTER_NAME_FORMAT {
  ComputerNameNetBIOS,
  ComputerNameDnsHostname,
  ComputerNameDnsDomain,
  ComputerNameDnsFullyQualified,
  ComputerNamePhysicalNetBIOS,
  ComputerNamePhysicalDnsHostname,
  ComputerNamePhysicalDnsDomain,
  ComputerNamePhysicalDnsFullyQualified,
  ComputerNameMax
} COMPUTER_NAME_FORMAT ;

Enumeration Values

ComputerNameNetBIOS
The NetBIOS name of the local computer or the cluster associated with the local computer. This name is limited to MAX_COMPUTERNAME_LENGTH + 1 characters and may be a truncated version of the DNS host name. For example, if the DNS host name is "corporate-mail-server", the NetBIOS name would be "corporate-mail-".

You cannot use this value with the SetComputerNameEx function.

ComputerNameDnsHostname
The DNS name of the local computer or the cluster associated with the local computer.

You cannot use this value with SetComputerNameEx.

ComputerNameDnsDomain
The name of the DNS domain assigned to the local computer or the cluster associated with the local computer.

You cannot use this value with SetComputerNameEx.

ComputerNameDnsFullyQualified
The fully qualified DNS name that uniquely identifies the local computer or the cluster associated with the local computer.

This name is a combination of the DNS host name and the DNS domain name, using the form HostName.DomainName. For example, if the DNS host name is "corporate-mail-server" and the DNS domain name is "microsoft.com", the fully qualified DNS name is "corporate-mail-server.microsoft.com".

You cannot use this value with SetComputerNameEx.

ComputerNamePhysicalNetBIOS
The NetBIOS name of the local computer. On a cluster, this is the NetBIOS name of the local node on the cluster.
ComputerNamePhysicalDnsHostname
The DNS host name of the local computer. On a cluster, this is the DNS host name of the local node on the cluster.
ComputerNamePhysicalDnsDomain
The name of the DNS domain assigned to the local computer. On a cluster, this is the DNS domain of the local node on the cluster.
ComputerNamePhysicalDnsFullyQualified
The fully qualified DNS name that uniquely identifies the computer. On a cluster, this is the fully qualified DNS name of the local node on the cluster. The fully qualified DNS name is a combination of the DNS host name and the DNS domain name, using the form HostName.DomainName.

You cannot use this value with SetComputerNameEx.

ComputerNameMax
Not used.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.

See Also

System Information Overview, System Information Enumeration Types, GetComputerNameEx, SetComputerNameEx


EXTENDED_NAME_FORMAT

The EXTENDED_NAME_FORMAT enumeration type contains values that specify a format for a directory service object name.

typedef enum {
    NameUnknown = 0,
    NameFullyQualifiedDN = 1,
    NameSamCompatible = 2,
    NameDisplay = 3,
    NameUniqueId = 6,
    NameCanonical = 7,
    NameUserPrincipal = 8,
    NameCanonicalEx = 9,
    NameServicePrincipal = 10
} EXTENDED_NAME_FORMAT, *PEXTENDED_NAME_FORMAT;

Enumeration Values

NameUnknown
Unknown name type.
NameFullyQualifiedDN
Fully qualified distinguished name (for example, CN=John Smith,OU=Users,DC=Engineering,DC=Microsoft,DC=Com).
NameSamCompatible
Windows NT® 4.0 account name (for example, Engineering\JSmith). The domain-only version includes trailing backslashes (\\).
NameDisplay
A "friendly" display name (for example, John Smith). The display name is not necessarily the defining relative distinguished name (RDN).
NameUniqueId
GUID string that the IIDFromString function returns (for example, {4fa050f0-f561-11cf-bdd9-00aa003a77b6}).
NameCanonical
Complete canonical name (for example, engineering.microsoft.com/software/someone). The domain-only version includes a trailing forward slash (/).
NameUserPrincipal
User principal name (for example, someone@engineering.microsoft.com).
NameCanonicalEx
Same as NameCanonical except that the rightmost forward slash (/) is replaced with a newline character (\n), even in a domain-only case (for example, engineering.microsoft.com/software\nsomeone).
NameServicePrincipal
Generalized service principal name (for example, www/www.microsoft.com@microsoft.com).

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Secext.h; include Security.h.

See Also

System Information Overview, System Information Enumeration Types, GetComputerObjectName, GetUserNameEx, TranslateName


System Shutdown

The system shutdown functions and messages allow applications to log off the current user, shut down the system, or lock the workstation.

  • About System Shutdown
  • Using System Shutdown
  • System Shutdown Reference


About System Shutdown

System shutdown brings the system to a condition in which it is safe to turn off the computer. All file-system buffers are flushed to the disk, then a message box is displayed informing the user that the computer can be turned off. There is also a reboot option that will restart the computer, rather than display this system shutdown message box. For more information, see How to Shut Down the System.

Logging off stops all processes associated with the security context of the process that called the exit function, logs the current user off the system, and displays the logon dialog box. For more information, see How to Log Off the Current User.

Locking the workstation protects the display from unauthorized use whenever you leave your computer. To unlock the workstation, you must log in. For more information, see How to Lock the Workstation.


How to Shut Down the System

There are two ways for an application to shut down local or remote computers:

  • Shut down the system.
  • Shut down the system and restart it.

Windows NT/2000 or later: The calling process must have the SE_SHUTDOWN_NAME privilege to shut down the system.

To shut down the system, use the ExitWindowsEx function. The system sends the WM_QUERYENDSESSION message to each window, unless you call ExitWindowsEx with the EXW_FORCE flag. The applications perform any cleanup while processing WM_QUERYENDSESSION, and return TRUE to indicate that they can be terminated. If you use EXW_FORCE, applications may lose data. For more information, see Shutting Down.

Windows NT/2000 or later: The InitiateSystemShutdown function starts a timer and displays a dialog box that prompts the user to log off. While the dialog box is displayed, the AbortSystemShutdown function can stop the timer and prevent the computer from shutting down. However, if the timer expires, the computer is shut down. InitiateSystemShutdown can also restart the computer following a shutdown operation. For more information, see Displaying the Shutdown Dialog Box.


How to Log Off the Current User

To log off the current user, call the ExitWindows or ExitWindowsEx function.

By default, when an application uses ExitWindows or ExitWindowsEx to log off, the system sends the WM_QUERYENDSESSION message to each window. Applications agree to terminate by returning TRUE when they receive this message. If any application returns FALSE, the log-off operation is canceled.

Windows NT/2000 or later: When an application returns TRUE for WM_QUERYENDSESSION, it receives the WM_ENDSESSION message and it is terminated, regardless of how the other applications respond to the WM_QUERYENDSESSION message.

Windows 95/98/Me: After all applications return TRUE for WM_QUERYENDSESSION, they receive the WM_ENDSESSION and they are terminated.

To force all applications to terminate, use ExitWindowsEx, and specify the EXW_FORCE flag. This prevents the system from sending WM_QUERYENDSESSION messages.

The system also sends the CTRL_LOGOFF_EVENT control signal to every process during a log-off operation. A console application can register a HandlerRoutine to process these messages.


How to Lock the Workstation

To lock the workstation, call the LockWorkStation function. The system displays the Lock Workstation dialog box. The dialog box text says that the workstation is in use and has been locked by the user. The workstation can be unlocked by the user or an administrator. To unlock the system, press Ctrl+Alt+Del and log in.

The LockWorkStation function is callable only by processes running on the interactive desktop. In addition, the user must be logged on, and the workstation cannot already be locked.


Receiving Shutdown Notification

Applications with a window and message queue receive shutdown notification through the WM_QUERYENDSESSION message.

Console applications receive shutdown notification in their handler routines. To register a console handler, use the SetConsoleCtrlHandler function.

Service applications receive shutdown notification in their handler routines. To register a service control handler, use the RegisterServiceCtrlHandlerEx function.


Using System Shutdown

  • Logging Off
  • Shutting Down
  • Displaying the Shutdown Dialog Box


Logging Off

The ExitWindows function logs off the current user. All applications must agree to terminate before the user logs off. If any application returns FALSE when it processes the WM_QUERYENDSESSION message, the user is not logged off. If your application handles the WM_QUERYENDSESSION message, you can allow the user to cancel the log-off operation, even if another application or the system originated the end-session request.

The following example logs off the current user, unless the user clicks the No button in the message box displayed when the application receives the WM_QUERYENDSESSION message.

// Log off the current user.

ExitWindows(0, 0);

// Process the message in the application's window procedure.

case WM_QUERYENDSESSION:
{
    int r;
    r = MessageBox(NULL, "Shut down?","WM_QUERYENDSESSION", MB_YESNO);

    // Return TRUE to allow shutdown, FALSE to stop.

    return r == IDYES;
    break;
}


Shutting Down

You can use the ExitWindowsEx function to shut down the system. Shutting down flushes file buffers to disk and brings the system to a condition in which it is safe to turn off the computer.

Windows NT/2000 or later: The following example enables the SE_SHUTDOWN_NAME privilege and then shuts down the system.

HANDLE hToken;
TOKEN_PRIVILEGES tkp;

// Get a token for this process.

if (!OpenProcessToken(GetCurrentProcess(),
        TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    error("OpenProcessToken");

// Get the LUID for the shutdown privilege.

LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
        &tkp.Privileges[0].Luid);

tkp.PrivilegeCount = 1;  // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

// Get the shutdown privilege for this process.

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
        (PTOKEN_PRIVILEGES)NULL, 0);

// Cannot test the return value of AdjustTokenPrivileges.

if (GetLastError() != ERROR_SUCCESS)
    error("AdjustTokenPrivileges");

// Shut down the system and force all applications to close.

if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0))
    error("ExitWindowsEx");

For more information about setting security privileges, see Privileges.


Displaying the Shutdown Dialog Box

Windows NT/2000 or later: The following example uses the InitiateSystemShutdown function to begin the system shutdown process on the computer on which is user is logged on. The application must first enable the SE_SHUTDOWN_NAME privilege.

HANDLE hToken;              // handle to process token
TOKEN_PRIVILEGES tkp;       // pointer to token structure

BOOL fResult;               // system shutdown flag

// Get the current process token handle so we can get shutdown
// privilege.

if (!OpenProcessToken(GetCurrentProcess(),
        TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    ErrorHandler("OpenProcessToken failed.");

// Get the LUID for shutdown privilege.

LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
        &tkp.Privileges[0].Luid);

tkp.PrivilegeCount = 1;  // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

// Get shutdown privilege for this process.

AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
    (PTOKEN_PRIVILEGES) NULL, 0);

// Cannot test the return value of AdjustTokenPrivileges.

if (GetLastError() != ERROR_SUCCESS)
    ErrorHandler("AdjustTokenPrivileges enable failed.");

// Display the shutdown dialog box and start the time-out countdown.

fResult = InitiateSystemShutdown(
    NULL,                                  // shut down local computer
    "Click on the main window and press \
     the Escape key to cancel shutdown.",  // message to user
    20,                                    // time-out period
    FALSE,                                 // ask user to close apps
    TRUE);                                 // reboot after shutdown

if (!fResult)
{
    ErrorHandler("InitiateSystemShutdown failed.");
}

// Disable shutdown privilege.

tkp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
        (PTOKEN_PRIVILEGES) NULL, 0);

if (GetLastError() != ERROR_SUCCESS)
{
    ErrorHandler("AdjustTokenPrivileges disable failed.");
}

If the AbortSystemShutdown function is executed in the time-out period specified by InitiateSystemShutdown, the system does not shut down. In this example, the user can prevent the system from shutting down by clicking on the application's main window and pressing the ESC key. The example processes the keystroke by calling AbortSystemShutdown.

HANDLE hToken;              // handle to process token
TOKEN_PRIVILEGES tkp;       // pointer to token structure

BOOL fResult;               // system shutdown flag

case WM_KEYDOWN:

    // Process only the Escape key.

    if (wParam != VK_ESCAPE)
    {
        break;
    }

    // Get the current process token handle  so we can get shutdown
    // privilege.

    if (!OpenProcessToken(GetCurrentProcess(),
            TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    {
        ErrorHandler("OpenProcessToken failed.");
    }

    // Get the LUID for shutdown privilege.

    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,
            &tkp.Privileges[0].Luid);

    tkp.PrivilegeCount = 1;  // one privilege to set
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    // Get shutdown privilege for this process.

    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
        (PTOKEN_PRIVILEGES)NULL, 0);

    // Cannot test the return value of AdjustTokenPrivileges.

    if (GetLastError() != ERROR_SUCCESS)
    {
        ErrorHandler("AdjustTokenPrivileges enable failed.");
    }

    // Prevent the system from shutting down.

    fResult = AbortSystemShutdown(NULL);

    if (!fResult)
    {
        ErrorHandler("AbortSystemShutdown failed.");
    }

    // Disable shutdown privilege.

    tkp.Privileges[0].Attributes = 0;
    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
        (PTOKEN_PRIVILEGES) NULL, 0);

    if (GetLastError() != ERROR_SUCCESS)
    {
        ErrorHandler("AdjustTokenPrivileges disable failed.");
    }

    break;


System Shutdown Reference

The following elements are used with system shutdown.

  • System Shutdown Functions
  • System Shutdown Messages


System Shutdown Functions

The following functions are used with system shutdown.

Function | Description
AbortSystemShutdown | Stops a system shutdown started by using the InitiateSystemShutdown function.
ExitWindows | Logs off the current user.
ExitWindowsEx | Either logs off the current user, shuts down the system, or shuts down and restarts the system.
InitiateSystemShutdown | Initiates a shutdown and optional restart of the specified computer.
InitiateSystemShutdownEx | Initiates a shutdown and optional restart of the specified computer.
LockWorkStation | Locks the workstation's display, protecting it from unauthorized use.


AbortSystemShutdown

The AbortSystemShutdown function stops a system shutdown started by using the InitiateSystemShutdown function.

BOOL AbortSystemShutdown(
  LPTSTR lpMachineName   // computer name
);

Parameters

lpMachineName
[in] Pointer to the null-terminated string that specifies the network name of the computer where the shutdown is to be stopped. If lpMachineName is NULL or an empty string, the function stops the shutdown on the local computer.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

The InitiateSystemShutdown function displays a dialog box that notifies the user that the system is shutting down. During the InitiateSystemShutdown time-out period, the AbortSystemShutdown function can prevent the system from shutting down.

To stop the local computer from shutting down, the calling process must have the SE_SHUTDOWN_NAME privilege. To stop a remote computer from shutting down, the calling process must have the SE_REMOTE_SHUTDOWN_NAME privilege on the remote computer. By default, users can enable the SE_SHUTDOWN_NAME privilege on the computer they are logged onto, and administrators can enable the SE_REMOTE_SHUTDOWN_NAME privilege on remote computers.

Common reasons for failure include an invalid computer name, an inaccessible computer, or insufficient privilege.

For an example, see Displaying the Shutdown Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Shutdown Overview, System Shutdown Functions, InitiateSystemShutdown


ExitWindows

The ExitWindows function logs off the current user. It sends the WM_QUERYENDSESSION message to determine if they can be terminated.

To shut down the system, or shut down and restart the system, use the ExitWindowsEx function.

BOOL ExitWindows(
  DWORD dwReserved,  // reserved; must be zero
  UINT uReserved     // reserved; must be zero
);

Parameters

dwReserved
Reserved; must be zero.
uReserved
Reserved; must be zero.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

Windows NT/2000 or later: The ExitWindows function asks applications if they want to terminate by sending WM_QUERYENDSESSION to the main window of all running applications.

Windows 95/98/Me: The ExitWindows function sends WM_QUERYENDSESSION to all applications except the one that called ExitWindows.

An application agrees to terminate by returning TRUE when it receives this message (or by allowing the DefWindowProc function to process the message). If any application returns FALSE when it receives the WM_QUERYENDSESSION message, the shutdown is canceled.

After the system processes the results of the WM_QUERYENDSESSION message, it sends the WM_ENDSESSION message with the wParam parameter set to TRUE if the system is shutting down and to FALSE if it is not.

The system does not allow new applications to start up during the shutdown process.

For an example, see Logging Off.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

System Shutdown Overview, System Shutdown Functions, DefWindowProc, ExitWindowsEx


ExitWindowsEx

The ExitWindowsEx function either logs off the current user, shuts down the system, or shuts down and restarts the system. It sends the WM_QUERYENDSESSION message to all applications to determine if they can be terminated.

BOOL ExitWindowsEx(
  UINT uFlags,       // shutdown operation
  DWORD dwReserved   // reserved
);

Parameters

uFlags
[in] Specifies the type of shutdown. This parameter must include one of the following values.
Value | Meaning
EWX_LOGOFF | Shuts down all processes running in the security context of the process that called the ExitWindowsEx function. Then it logs the user off.
EWX_POWEROFF Shuts down the system and turns off the power. The system must support the power-off feature.

Windows NT/2000 or later: The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.

EWX_REBOOT Shuts down the system and then restarts the system.

Windows NT/2000 or later: The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.

EWX_SHUTDOWN Shuts down the system to a point at which it is safe to turn off the power. All file buffers have been flushed to disk, and all running processes have stopped. If the system supports the power-off feature, the power is also turned off.

Windows NT/2000 or later: The calling process must have the SE_SHUTDOWN_NAME privilege. For more information, see the following Remarks section.

This parameter can optionally include the following values.
Value | Meaning
EWX_FORCE | Forces processes to terminate. When this flag is set, the system does not send the WM_QUERYENDSESSION and WM_ENDSESSION messages. This can cause the applications to lose data. Therefore, you should only use this flag in an emergency.
EWX_FORCEIFHUNG | Windows 2000 or later: Forces processes to terminate if they do not respond to the WM_QUERYENDSESSION or WM_ENDSESSION message. This flag is ignored if EWX_FORCE is used.

dwReserved
[in] Reserved; this parameter is ignored.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

The ExitWindowsEx function returns as soon as it has initiated the shutdown. The shutdown or logoff then proceeds asynchronously.

To set a shutdown priority for an application relative to other applications in the system, use the SetProcessShutdownParameters function.

During a shutdown or log-off operation, applications that are shut down are allowed a specific amount of time to respond to the shutdown request. If the time expires, the system displays a dialog box that allows the user to forcibly shut down the application, to retry the shutdown, or to cancel the shutdown request. If the EWX_FORCE value is specified, the system always forces applications to close and does not display the dialog box.

Windows 2000 or later: If the EWX_FORCEIFHUNG value is specified, the system forces hung applications to close and does not display the dialog box.

Windows 95/98/Me: Because of the design of the shell, calling ExitWindowsEx with EWX_FORCE fails to completely log off the user (the system terminates the applications and displays the Enter Windows Password dialog box, however, the user's desktop remains.) To log off the user forcibly, terminate the Explorer process before calling ExitWindowsEx with EWX_LOGOFF and EWX_FORCE.

Console processes receive a separate notification message, CTRL_SHUTDOWN_EVENT or CTRL_LOGOFF_EVENT, as the situation warrants. A console process routes these messages to its HandlerRoutine function. ExitWindowsEx sends these notification messages asynchronously; thus, an application cannot assume that the console notification messages have been handled when a call to ExitWindowsEx returns.

Windows NT/2000 or later: To shut down or restart the system, the calling process must use the AdjustTokenPrivileges function to enable the SE_SHUTDOWN_NAME privilege. For more information about security privileges, see Privileges.

Windows 95/98/Me: ExitWindowEx does not work from a console application, as it does on Windows NT/Windows 2000.

For an example, see Shutting Down.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

System Shutdown Overview, System Shutdown Functions, AdjustTokenPrivileges, HandlerRoutine, SetProcessShutdownParameters


InitiateSystemShutdown

The InitiateSystemShutdown function initiates a shutdown and optional restart of the specified computer.

To record a reason for the shutdown in the event log, call the InitiateSystemShutdownEx function.

BOOL InitiateSystemShutdown(
  LPTSTR lpMachineName,      // computer name
  LPTSTR lpMessage,          // message to display
  DWORD dwTimeout,           // length of time to display
  BOOL bForceAppsClosed,     // force closed option
  BOOL bRebootAfterShutdown  // reboot option
);

Parameters

lpMachineName
[in] Pointer to the null-terminated string that specifies the network name of the computer to shut down. If lpMachineName is NULL or an empty string, the function shuts down the local computer.
lpMessage
[in] Pointer to a null-terminated string that specifies a message to display in the shutdown dialog box. This parameter can be NULL if no message is required.
dwTimeout
[in] Specifies the time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, the shutdown can be stopped by the AbortSystemShutdown function.

If dwTimeout is not zero, InitiateSystemShutdown displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, displays the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows in the system. The dialog box can be moved but not closed. A timer counts down the remaining time before a forced shutdown.

If dwTimeout is zero, the computer shuts down without displaying the dialog box, and the shutdown cannot be stopped by AbortSystemShutdown.

bForceAppsClosed
[in] Specifies whether applications with unsaved changes are to be forcibly closed. If this parameter is TRUE, such applications are closed. If this parameter is FALSE, a dialog box is displayed prompting the user to close the applications.
bRebootAfterShutdown
[in] Specifies whether the computer is to restart immediately after shutting down. If this parameter is TRUE, the computer is to restart. If this parameter is FALSE, the system flushes all caches to disk, clears the screen, and displays a message indicating that it is safe to power down.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

To shut down the local computer, the calling thread must have the SE_SHUTDOWN_NAME privilege. To shut down a remote computer, the calling thread must have the SE_REMOTE_SHUTDOWN_NAME privilege on the remote computer. By default, users can enable the SE_SHUTDOWN_NAME privilege on the computer they are logged onto, and administrators can enable the SE_REMOTE_SHUTDOWN_NAME privilege on remote computers.

Common reasons for failure include an invalid or inaccessible computer name or insufficient privilege.

For an example, see Displaying the Shutdown Dialog Box.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

See Also

System Shutdown Overview, System Shutdown Functions, AbortSystemShutdown, InitiateSystemShutdownEx


InitiateSystemShutdownEx

The InitiateSystemShutdownEx function initiates a shutdown and optional restart of the specified computer.

BOOL InitiateSystemShutdownEx(
  LPTSTR lpMachineName,       // computer name
  LPTSTR lpMessage,           // message to display
  DWORD dwTimeout,            // length of time to display
  BOOL bForceAppsClosed,      // force closed option
  BOOL bRebootAfterShutdown,  // reboot option
  DWORD dwReason              // shutdown reason
);

Parameters

lpMachineName
[in] Pointer to the null-terminated string that specifies the network name of the computer to shut down. If lpMachineName is NULL or an empty string, the function shuts down the local computer.
lpMessage
[in] Pointer to a null-terminated string that specifies a message to display in the shutdown dialog box. This parameter can be NULL if no message is required.
dwTimeout
[in] Specifies the time (in seconds) that the shutdown dialog box should be displayed. While this dialog box is displayed, shutdown can be stopped by the AbortSystemShutdown function.

If dwTimeout is not zero, InitiateSystemShutdownEx displays a dialog box on the specified computer. The dialog box displays the name of the user who called the function, displays the message specified by the lpMessage parameter, and prompts the user to log off. The dialog box beeps when it is created and remains on top of other windows in the system. The dialog box can be moved but not closed. A timer counts down the remaining time before a forced shutdown.

If dwTimeout is zero, the computer shuts down without displaying the dialog box, and the shutdown cannot be stopped by AbortSystemShutdown.

bForceAppsClosed
[in] Specifies whether applications with unsaved changes are to be forcibly closed. If this parameter is TRUE, such applications are closed. If this parameter is FALSE, a dialog box is displayed prompting the user to close the applications.
bRebootAfterShutdown
[in] Specifies whether the computer is to restart immediately after shutting down. If this parameter is TRUE, the computer is to restart. If this parameter is FALSE, the system flushes all caches to disk, clears the screen, and displays a message indicating that it is safe to power down.
dwReason
[in] Specifies the reason for initiating the shutdown. This reason is recorded in the event log with event number 6006.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

To shut down the local computer, the calling thread must have the SE_SHUTDOWN_NAME privilege. To shut down a remote computer, the calling thread must have the SE_REMOTE_SHUTDOWN_NAME privilege on the remote computer. By default, users can enable the SE_SHUTDOWN_NAME privilege on the computer they are logged onto, and administrators can enable the SE_REMOTE_SHUTDOWN_NAME privilege on remote computers.

Common reasons for failure include an invalid or inaccessible computer name or insufficient privilege. The error ERROR_SHUTDOWN_IN_PROGRESS is returned if a shutdown is already in progress on the specified computer.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winreg.h; include Windows.h.
Library: Use Advapi32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows 2000.

See Also

System Shutdown Overview, System Shutdown Functions, AbortSystemShutdown


LockWorkStation

The LockWorkStation function locks the workstation's display, protecting it from unauthorized use.

BOOL LockWorkStation(VOID);

Parameters

This function has no parameters.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

This function has the same result as pressing Ctrl+Alt+Del and clicking Lock Workstation. To unlock the workstation, the user must log in.

Common reasons for failure include no user is logged on, the workstation is already locked, the process is not running on the interactive desktop, or the request is denied by the Graphical Identification and Authentication (GINA) DLL.

Requirements

Windows NT/2000 or later: Requires Windows 2000 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winuser.h; include Windows.h.
Library: Use User32.lib.

See Also

System Shutdown Overview, System Shutdown Functions


System Shutdown Messages

The following messages are used with system shutdown.

WM_ENDSESSION
WM_QUERYENDSESSION


WM_ENDSESSION

The WM_ENDSESSION message is sent to an application after the system processes the results of the WM_QUERYENDSESSION message. The WM_ENDSESSION message informs the application whether the session is ending.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_ENDSESSION
  WPARAM wParam,   // end-session option
  LPARAM lParam    // logoff option
);

Parameters

wParam
Specifies whether the session is being ended. If the session is being ended, this parameter is TRUE; otherwise, it is FALSE.
lParam
Specifies whether the user is logging off or shutting down the system. If this parameter includes the ENDSESSION_LOGOFF value, the user if logging off. (Note that this parameter is a bit mask. To test for this value, use a bitwise operation; do not test for equality.)

Windows 2000 or later: If this parameter is zero, the system is shutting down.

Return Values

If an application processes this message, it should return zero.

Remarks

If the wParam parameter is TRUE, the session can end any time after all applications have returned from processing this message. Therefore, an application should perform all tasks required for termination before returning from this message.

The application need not call the DestroyWindow or PostQuitMessage function when the session is ending.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

System Shutdown Overview, System Shutdown Messages, DestroyWindow, PostQuitMessage, WM_QUERYENDSESSION


WM_QUERYENDSESSION

The WM_QUERYENDSESSION message is sent when the user chooses to end the session or when an application calls the ExitWindows function. If any application returns zero, the session is not ended. The system stops sending WM_QUERYENDSESSION messages as soon as one application returns zero.

After processing this message, the system sends the WM_ENDSESSION message with the wParam parameter set to the results of the WM_QUERYENDSESSION message.

A window receives this message through its WindowProc function.

LRESULT CALLBACK WindowProc(
  HWND hwnd,       // handle to window
  UINT uMsg,       // WM_QUERYENDSESSION
  WPARAM wParam,   // not used
  LPARAM lParam    // logoff option
);

Parameters

wParam
This parameter is reserved for future use.
lParam
Specifies whether the user is logging off or shutting down the system. If this parameter includes the ENDSESSION_LOGOFF value, the user if logging off. (Note that this parameter is a bit mask. To test for this value, use a bitwise operation; do not test for equality.)

Windows 2000 or later: If this parameter is zero, the system is shutting down.

Return Values

If an application can terminate conveniently, it should return TRUE; otherwise, it should return FALSE.

Remarks

By default, the DefWindowProc function returns TRUE for this message.

Windows NT/2000 or later: When an application returns TRUE for this message, it receives the WM_ENDSESSION message and it is terminated, regardless of how the other applications respond to the WM_QUERYENDSESSION message.

Windows 95/98/Me: After all applications return TRUE for this message, they receive the WM_ENDSESSION and they are terminated.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

System Shutdown Overview, System Shutdown Messages, DefWindowProc, ExitWindows, WM_ENDSESSION


Time

The date and time functions retrieve and set the date and time for the system and individual files. This overview describes how to use these functions to examine and modify dates and times.

  • About Time
  • Using Time
  • Time Reference

See Also

  • File I/O
  • File Systems


About Time

There are five time formats. Time-related functions return time in one of these formats. You can also use the time functions to convert between time formats for ease of comparison and display. The following table summarizes the time formats.

Format | Type | Description
System | SYSTEMTIME | Year, month, day, hour, second, and millisecond, taken from the internal hardware clock.
File | FILETIME | 100-nanosecond intervals since January 1, 1601.
Local | SYSTEMTIME or FILETIME | A system time or file time converted to the system's local time zone.
MS-DOS | WORD | A packed word for the date, another for the time.
Windows | DWORD | The number of milliseconds since the system booted; a quantity that cycles every 49.7 days.

For more information, see the following topics.

  • System Time
  • Local Time
  • File Times
  • MS-DOS Date and Time
  • Windows Time


System Time

System time is the current date and time of day. The system keeps time so that your applications have ready access to accurate time. The system bases system time on coordinated universal time (UTC). UTC-based time is loosely defined as the current date and time of day in Greenwich, England.

When the system first starts, it sets the system time to a value based on the real-time clock of the computer and then regularly updates the time. To retrieve the system time, use the GetSystemTime function. GetSystemTime copies the time to a SYSTEMTIME structure that contains individual members for month, day, year, weekday, hour, minute, second, and milliseconds. It is easy to display this format to a user.

You can also obtain the system time in file time format using the GetSystemTimeAsFileTime function. GetSystemTimeAsFileTime copies the time to a FILETIME structure.

To set the system time, use the SetSystemTime function. SetSystemTime assumes you have specified a UTC-based time. If you change the system time, you should send the WM_TIMECHANGE message to all top-level windows by using the SendMessage function.

The GetSystemTimeAdjustment and SetSystemTimeAdjustment functions synchronize the time-of-day clock with another time source using a periodic time adjustment applied at each clock interrupt.


Local Time

While the system uses UTC-based time internally, your applications will generally display the local time — the date and time of day for your time zone. Therefore, to ensure correct results, you must be aware of whether a function expects to receive a UTC-based time or a local time, and whether the function returns a UTC-based time or a local time.

The current time-zone settings control how the system converts between UTC and local time. You can retrieve the current time-zone settings by using the GetTimeZoneInformation function. The function copies the result to a TIME_ZONE_INFORMATION structure and returns a value indicating whether local time is currently in standard time or daylight saving time. You can set the time-zone settings by using the SetTimeZoneInformation function.

To retrieve the local time, use the GetLocalTime function. GetLocalTime converts the system time to a local time based on the current time-zone settings and copies the result to a SYSTEMTIME structure. You can set the system time by using the SetLocalTime function. SetLocalTime assumes you have specified a local time and converts to UTC before setting the system time.

Windows NT/2000 or later: When you call SetLocalTime, the system uses the current time zone information, including the daylight saving time setting, to perform the conversion. Note that the system uses the daylight saving time setting of the current time, not the new time you are setting. Therefore, to ensure the correct result, call SetLocalTime a second time, now that the first call has updated the daylight saving time setting.

To convert a UTC-based time to a local time, use the SystemTimeToTzSpecificLocalTime function. To convert a local time to a UTC-based time, use the TzSpecificLocalTimeToSystemTime function.


File Times

A file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 A.M. January 1, 1601 (UTC). The system records file times whenever applications create, access, and write to files. Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour.

To retrieve the file times for a specified file, use the GetFileTime function. GetFileTime copies the creation, last access, and last write times to individual FILETIME structures. You can also retrieve file times using the FindFirstFile and FindNextFile functions. These functions copy the file times to FILETIME structures in a WIN32_FIND_DATA structure.

To set the file times for a file, use the SetFileTime function. This function lets you modify creation, last access, and last write times without changing the content of the file. You can compare the times of different files by using the CompareFileTime function. The function compares two file times and returns a value indicating which time is greater or returns zero if the times are equal.

If you plan to modify file times for specified files, you can convert a date and time of day to a file time by using the SystemTimeToFileTime function. You can also obtain the system time in a FILETIME structure by calling the GetSystemTimeAsFileTime function.

To make a file time easy to display to a user, use the FileTimeToSystemTime function. FileTimeToSystemTime converts the file time and copies the month, day, year, and time of day from the file time to a SYSTEMTIME structure.

File Times and Daylight Saving Time

You must take care using file times if the user has set the system to automatically adjust for daylight saving time.

To convert a file time to local time, use the FileTimeToLocalFileTime function. However, FileTimeToLocalFileTime uses the current settings for the time zone and daylight saving time. Therefore, if it is daylight saving time, it will take daylight saving time into account, even if the file time you are converting is in standard time.

FAT records times on disk in local time. GetFileTime retrieves cached UTC times from FAT. When it becomes daylight saving time, the time retrieved by GetFileTime will be off an hour, because the cache has not been updated. When you restart the machine, the cached time retrieved by GetFileTime will be correct. FindFirstFile retrieves the local time from FAT and converts it to UTC using the current settings for the time zone and daylight saving time. Therefore, if it is daylight saving time, FindFirstFile will take daylight saving time into account, even if the file time you are converting is in standard time.

NTFS records times on disk in UTC. To account for daylight saving time when converting a file time to a local time, use the following functions instead of FileTimeToLocalFileTime:

  1. FileTimeToSystemTime
  2. SystemTimeToTzSpecificLocalTime
  3. SystemTimeToFileTime


MS-DOS Date and Time

MS-DOS date and MS-DOS time are packed 16-bit values that specify the month, day, year, and time of day an MS-DOS file was last written to. MS-DOS records the date and time whenever an MS-DOS application creates or writes to a file. MS-DOS applications retrieve this date and time using MS-DOS functions. When you use the GetFileTime function to retrieve the file times for files that were created by MS-DOS, GetFileTime automatically converts MS-DOS dates and times to UTC-based times.

If you encounter an MS-DOS date and time that has not been converted, you can convert it to a UTC-based time by using the DosDateTimeToFileTime function. This function copies the converted date and time to a FILETIME structure. You can convert the value back to an MS-DOS date and time by using the FileTimeToDosDateTime function.


Windows Time

Windows time is the number of milliseconds elapsed since the system started running. This format exists primarily for backward compatibility with 16-bit Windows. To ensure that applications designed for 16-bit Windows continue to run successfully, the GetTickCount function returns the current Windows time.

You typically use GetTickCount to compare the current Windows time with the time returned by the GetMessageTime function. GetMessageTime returns the Windows time when the specified message was created. GetTickCount is limited to the resolution of the system timer.

Windows NT 3.5 and later: The system timer runs at approximately 10ms.

Windows NT 3.1: The system timer runs at approximately 16ms.

Windows 95/98/Me: The system timer runs at approximately 55ms.

If you need a higher resolution timer, use a multimedia timer or a high-resolution timer.

Windows time is stored as a 32-bit value, which means the system can record no more than 2^32 millisecond intervals before the 32-bit value overflows to zero. This is approximately 49.7 days. If you use Windows time, check for the overflow condition when comparing times.

Windows NT/2000 or later: You can use the System Up Time performance counter to obtain the time elapsed since the computer was started.


Using Time

  • Retrieving the last-write time
  • Changing a file time to the current time
  • Setting the system time
  • Converting a time_t value to a file time


Retrieving the Last-Write Time

The following example uses the GetFileTime function to retrieve the last-write time for a file. It converts the time to local time based on the current time-zone settings, and creates a date and time string that can be shown to the user.

// GetLastWriteTime - retrieves the last-write time and converts the
//                   time to a string
// Return value - TRUE if successful, FALSE otherwise
// hFile      - must be a valid file handle
// lpszString - pointer to buffer to receive string

BOOL GetLastWriteTime(HANDLE hFile, LPSTR lpszString)
{
    FILETIME ftCreate, ftAccess, ftWrite, ftLocal;
    SYSTEMTIME stCreate;

    // Retrieve the file times for the file.
    if (!GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite))
        return FALSE;

    // Convert the last-write time to local time.
    if (!FileTimeToLocalFileTime(&ftWrite, &ftLocal))
        return FALSE;

    // Convert the local file time from UTC to system time.
    FileTimeToSystemTime(&ftLocal, &stCreate);

    // Build a string showing the date and time.
    wsprintf(lpszString, "%02d/%02d/%d  %02d:%02d",
        stCreate.wDay, stCreate.wMonth, stCreate.wYear,
        stCreate.wHour, stCreate.wMinute);

    return TRUE;
}


Changing a File Time to the Current Time

The following example sets the last-write time for a file to the current system time using the SetFileTime function.

// SetFileToCurrentTime - sets last write time to current system time
// Return value - TRUE if successful, FALSE otherwise
// hFile  - must be a valid file handle

BOOL SetFileToCurrentTime(HANDLE hFile)
{
    FILETIME ft;
    SYSTEMTIME st;
    BOOL f;

    GetSystemTime(&st);              // gets current time
    SystemTimeToFileTime(&st, &ft);  // converts to file time format
    f = SetFileTime(hf,              // sets last-write time for file
        (LPFILETIME) NULL, (LPFILETIME) NULL, &ft);

    return f;
}


Setting the System Time

The following example sets the system time using the SetSystemTime function.

// SetNewTime - sets system time
// Return value - TRUE if successful, FALSE otherwise
// hour     - new hour (0-23)
// minutes  - new minutes (0-59)

BOOL SetNewTime(WORD hour, WORD minutes)
{
    SYSTEMTIME st;
    char *pc;

    GetSystemTime(&st);       // gets current time
    st.wHour = hour;          // adjusts hours
    st.wMinute = minutes;     // and minutes
    if (!SetSystemTime(&st))  // sets system time
        return FALSE;
    return TRUE;
}


Converting a time_t Value to a File Time

The time functions included in the C run-time use the time_t type to represent the number of seconds elapsed since midnight, January 1, 1970. The following example converts a time_t value to a file time, using the Int32x32To64 function.

void TimetToFileTime( time_t t, LPFILETIME pft )
{
    LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000;
    pft->dwLowDateTime = (DWORD) ll;
    pft->dwHighDateTime = ll >>32;
}

After you have obtained a file time, you can convert this value to system time using the FileTimeToSystemTime function.


Time Reference

The following elements are used with time.

  • Time Functions
  • Time Structures
  • Time Messages


Time Functions

The following functions are used with system time.

Function | Description
GetSystemTime | Retrieves the current system date and time in UTC format.
GetSystemTimeAdjustment | Determines whether the system is applying periodic time adjustments to its time-of-day clock.
LocalFileTimeToFileTime | Converts a local file time to a file time based on UTC.
SetSystemTime | Sets the current system time and date.
SetSystemTimeAdjustment | Enables or disables periodic time adjustments to the system's time-of-day clock.
SystemTimeToFileTime | Converts a system time to a file time.
SystemTimeToTzSpecificLocalTime | Converts a UTC time to a specified time zone's corresponding local time.
TzSpecificLocalTimeToSystemTime | Converts a local time to a UTC time.

The following functions are used with local time.

Function | Description
FileTimeToLocalFileTime | Converts a UTC file time to a local file time.
GetLocalTime | Retrieves the current local date and time.
GetTimeZoneInformation | Retrieves the current time-zone parameters.
SetLocalTime | Sets the current local time and date.
SetTimeZoneInformation | Sets the current time-zone parameters.
SystemTimeToTzSpecificLocalTime | Converts a UTC time to a specified time zone's corresponding local time.
TzSpecificLocalTimeToSystemTime | Converts a local time to a UTC time.

The following functions are used with file time.

Function | Description
CompareFileTime | Compares two file times.
FileTimeToLocalFileTime | Converts a UTC file time to a local file time.
FileTimeToSystemTime | Converts a file time to system time format.
GetFileTime | Retrieves the date and time that a file was created, last accessed, and last modified.
GetSystemTimeAsFileTime | Retrieves the current system date and time in UTC format.
LocalFileTimeToFileTime | Converts a local file time to a file time based on UTC.
SetFileTime | Sets the date and time that a file was created, last accessed, or last modified.
SystemTimeToFileTime | Converts a system time to a file time.

The following functions are used with MS-DOS date and time.

Function | Description
DosDateTimeToFileTime | Converts MS-DOS date and time values to a file time.
FileTimeToDosDateTime | Converts a file time to MS-DOS date and time values.

The following functions are used with Windows time.

Function | Description
GetTickCount | Retrieves the number of milliseconds that have elapsed since the system was started.


CompareFileTime

The CompareFileTime function compares two file times.

LONG CompareFileTime(
  CONST FILETIME *lpFileTime1,  // first file time
  CONST FILETIME *lpFileTime2   // second file time
);

Parameters

lpFileTime1
[in] Pointer to a FILETIME structure that specifies the first file time.
lpFileTime2
[in] Pointer to a FILETIME structure that specifies the second file time.

Return Values

The return value is one of the following values.

Value | Meaning
–1 | First file time is less than second file time.
0 | First file time is equal to second file time.
1 | First file time is greater than second file time.

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, GetFileTime, FILETIME


DosDateTimeToFileTime

The DosDateTimeToFileTime function converts MS-DOS date and time values to a file time.

BOOL DosDateTimeToFileTime(
  WORD wFatDate,          // 16-bit MS-DOS date
  WORD wFatTime,          // 16-bit MS-DOS time
  LPFILETIME lpFileTime   // file time
);

Parameters

wFatDate
[in] Specifies the MS-DOS date. The date is a packed 16-bit value with the following format.
Bits | Contents
0–4 | Day of the month (1–31)
5–8 | Month (1 = January, 2 = February, and so on)
9–15 | Year offset from 1980 (add 1980 to get actual year)

wFatTime
[in] Specifies the MS-DOS time. The time is a packed 16-bit value with the following format.
Bits | Contents
0–4 | Second divided by 2
5–10 | Minute (0–59)
11–15 | Hour (0–23 on a 24-hour clock)

lpFileTime
[out] Pointer to a FILETIME structure to receive the converted file time.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, FILETIME, FileTimeToDosDateTime, FileTimeToSystemTime, SystemTimeToFileTime


FileTimeToDosDateTime

The FileTimeToDosDateTime function converts a file time to MS-DOS date and time values.

BOOL FileTimeToDosDateTime(
  CONST FILETIME *lpFileTime, // file time
  LPWORD lpFatDate,           // MS-DOS date
  LPWORD lpFatTime            // MS-DOS time
);

Parameters

lpFileTime
[in] Pointer to a FILETIME structure containing the file time to convert to MS-DOS date and time format.
lpFatDate
[out] Pointer to a variable to receive the MS-DOS date. The date is a packed 16-bit value with the following format.
Bits | Contents
0–4 | Day of the month (1–31)
5–8 | Month (1 = January, 2 = February, etc.)
9–15 | Year offset from 1980 (add 1980 to get actual year)

lpFatTime
[out] Pointer to a variable to receive the MS-DOS time. The time is a packed 16-bit value with the following format.
Bits | Contents
0–4 | Second divided by 2
5–10 | Minute (0–59)
11–15 | Hour (0–23 on a 24-hour clock)

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

The MS-DOS date format can represent only dates between 1/1/1980 and 12/31/2107; this conversion fails if the input file time is outside this range.

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, DosDateTimeToFileTime, FileTimeToSystemTime, SystemTimeToFileTime


FileTimeToLocalFileTime

The FileTimeToLocalFileTime function converts a file time to a local file time.

BOOL FileTimeToLocalFileTime(
  CONST FILETIME *lpFileTime,  // UTC file time to convert
  LPFILETIME lpLocalFileTime   // converted file time
);

Parameters

lpFileTime
[in] Pointer to a FILETIME structure containing the UTC-based file time to be converted into a local file time.
lpLocalFileTime
[out] Pointer to a FILETIME structure to receive the converted local file time. This parameter cannot be the same as the lpFileTime parameter.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

FileTimeToLocalFileTime uses the current settings for the time zone and daylight saving time. Therefore, if it is daylight saving time, this function will take daylight saving time into account, even if the time you are converting is in standard time.

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, FILETIME, LocalFileTimeToFileTime


FileTimeToSystemTime

The FileTimeToSystemTime function converts a file time to system time format.

BOOL FileTimeToSystemTime(
  CONST FILETIME *lpFileTime,  // file time to convert
  LPSYSTEMTIME lpSystemTime    // receives system time
);

Parameters

lpFileTime
[in] Pointer to a FILETIME structure containing the file time to convert to system date and time format.

This value must be less than 0x8000000000000000. Otherwise, the function fails.

lpSystemTime
[out] Pointer to a SYSTEMTIME structure to receive the converted file time.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

For an example, see Retrieving the Last-Write Time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, DosDateTimeToFileTime, FILETIME, FileTimeToDosDateTime, SYSTEMTIME, SystemTimeToFileTime


GetFileTime

The GetFileTime function retrieves the date and time that a file was created, last accessed, and last modified.

BOOL GetFileTime(
  HANDLE hFile,                 // handle to file
  LPFILETIME lpCreationTime,    // creation time
  LPFILETIME lpLastAccessTime,  // last access time
  LPFILETIME lpLastWriteTime    // last write time
);

Parameters

hFile
[in] Handle to the files for which to get dates and times. The file handle must have been created with GENERIC_READ access to the file.
lpCreationTime
[out] Pointer to a FILETIME structure to receive the date and time the file was created. This parameter can be NULL if the application does not require this information.
lpLastAccessTime
[out] Pointer to a FILETIME structure to receive the date and time the file was last accessed. The last access time includes the last time the file was written to, read from, or, in the case of executable files, run. This parameter can be NULL if the application does not require this information.
lpLastWriteTime
[out] Pointer to a FILETIME structure to receive the date and time the file was last written to. This parameter can be NULL if the application does not require this information.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

The FAT and NTFS file systems support the file creation, last access, and last write time values.

Windows NT/2000 or later: If you rename or delete a file, then restore it shortly thereafter, Windows NT searches the cache for file information to restore. Cached information includes its short/long name pair and creation time.

Note Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on Windows NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Therefore, GetFileTime may not return the same file time information set using the SetFileTime function. Furthermore, FAT records times on disk in local time. However, NTFS records times on disk in UTC. For more information, see File Times.

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

For an example, see Retrieving the Last-Write Time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, File Times, FILETIME, GetFileSize, GetFileType, SetFileTime


GetLocalTime

The GetLocalTime function retrieves the current local date and time.

VOID GetLocalTime(
  LPSYSTEMTIME lpSystemTime   // system time
);

Parameters

lpSystemTime
[out] Pointer to a SYSTEMTIME structure to receive the current local date and time.

Return Values

This function does not return a value.

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, GetSystemTime, SetLocalTime, SYSTEMTIME


GetSystemTime

The GetSystemTime function retrieves the current system date and time. The system time is expressed in Coordinated Universal Time (UTC).

VOID GetSystemTime(
  LPSYSTEMTIME lpSystemTime   // system time
);

Parameters

lpSystemTime
[out] Pointer to a SYSTEMTIME structure to receive the current system date and time.

Return Values

This function does not return a value.

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

For an example, see Changing a File Time to the Current Time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, GetLocalTime, GetSystemTimeAdjustment, SetSystemTime, SYSTEMTIME


GetSystemTimeAdjustment

The GetSystemTimeAdjustment function determines whether the system is applying periodic time adjustments to its time-of-day clock at each clock interrupt, along with the value and period of any such adjustments. Note that the period of such adjustments is equivalent to the time period between clock interrupts.

BOOL GetSystemTimeAdjustment(
  PDWORD lpTimeAdjustment,       // size of time adjustment
  PDWORD lpTimeIncrement,        // time between adjustments
  PBOOL lpTimeAdjustmentDisabled // disable option
);

Parameters

lpTimeAdjustment
[out] Pointer to a DWORD that the function sets to the number of 100-nanosecond units added to the time-of-day clock at each periodic time adjustment.
lpTimeIncrement
[out] Pointer to a DWORD that the function sets to the interval, counted in 100-nanosecond units, between periodic time adjustments. This interval is the time period between a system's clock interrupts.
lpTimeAdjustmentDisabled
[out] Pointer to a BOOL that the function sets to indicate whether periodic time adjustment is in effect.

A value of TRUE indicates that periodic time adjustment is disabled. At each clock interrupt, the system merely adds the interval between clock interrupts to the time-of-day clock. The system is free, however, to adjust its time-of-day clock using other techniques. Such other techniques may cause the time-of-day clock to noticeably jump when adjustments are made.

A value of FALSE indicates that periodic time adjustment is being used to adjust the time-of-day clock. At each clock interrupt, the system adds the time increment specified by SetSystemTimeAdjustment's dwTimeIncrement parameter to the time-of-day clock. The system will not interfere with the time adjustment scheme, and will not attempt to synchronize time of day on its own via other techniques.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

The GetSystemTimeAdjustment and SetSystemTimeAdjustment functions support algorithms that want to synchronize the time-of-day clock, reported by GetSystemTime and GetLocalTime, with another time source using a periodic time adjustment applied at each clock interrupt.

When periodic time adjustment is in effect, the system adds an adjusting value to the time-of-day clock at a periodic interval, at each clock interrupt. The GetSystemTimeAdjustment function lets a caller determine whether periodic time adjustment is enabled, and if it is, obtain the amount of each adjustment and the time between adjustments. The SetSystemTimeAdjustment function lets a caller enable or disable periodic time adjustment, and set the value of the adjusting increment.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, SetSystemTimeAdjustment, GetSystemTime, GetLocalTime


GetSystemTimeAsFileTime

The GetSystemTimeAsFileTime function retrieves the current system date and time. The information is in Coordinated Universal Time (UTC) format.

VOID GetSystemTimeAsFileTime(
  LPFILETIME lpSystemTimeAsFileTime  // file time
);

Parameters

lpSystemTimeAsFileTime
[out] Pointer to a FILETIME structure to receive the current system date and time in UTC format.

Return Values

This function does not return a value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, FILETIME, GetSystemTime, SYSTEMTIME, SystemTimeToFileTime


GetTickCount

The GetTickCount function retrieves the number of milliseconds that have elapsed since the system was started. It is limited to the resolution of the system timer. To obtain the system timer resolution, use the GetSystemTimeAdjustment function.

DWORD GetTickCount(VOID);

Parameters

This function has no parameters.

Return Values

The return value is the number of milliseconds that have elapsed since the system was started.

Remarks

The elapsed time is stored as a DWORD value. Therefore, the time will wrap around to zero if the system is run continuously for 49.7 days.

If you need a higher resolution timer, use a multimedia timer or a high-resolution timer.

Windows NT/2000 or later: To obtain the time elapsed since the computer was started, retrieve the System Up Time counter in the performance data in the registry key HKEY_PERFORMANCE_DATA. The value returned is an 8-byte value. For more information, see Performance Monitoring.

Example

The following example demonstrates how to handle timer wrap around.

DWORD dwStart = GetTickCount();

// Stop if this has taken too long
if( GetTickCount() - dwStart >= TIMELIMIT )
    Cancel();

Where TIMELIMIT is the time interval of interest to the application.

For an example, see Starting a Service.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions


GetTimeZoneInformation

The GetTimeZoneInformation function retrieves the current time-zone parameters. These parameters control the translations between Coordinated Universal Time (UTC) and local time.

DWORD GetTimeZoneInformation(
  LPTIME_ZONE_INFORMATION lpTimeZoneInformation // time zone
);

Parameters

lpTimeZoneInformation
[out] Pointer to a TIME_ZONE_INFORMATION structure to receive the current time-zone parameters.

Return Values

If the function succeeds, the return value is one of the following values:

Value | Meaning
TIME_ZONE_ID_UNKNOWN | The system cannot determine the current time zone. This error is also returned if you call the SetTimeZoneInformation function and supply the bias values but no transition dates. Windows NT/2000 or later: This value is returned if daylight saving time is not used in the current time zone, because there are no transition dates.
TIME_ZONE_ID_STANDARD | The system is operating in the range covered by the StandardDate member of the TIME_ZONE_INFORMATION structure. Windows 95/98/Me: This value is returned if daylight saving time is not used in the current time zone, because there are no transition dates.
TIME_ZONE_ID_DAYLIGHT | The system is operating in the range covered by the DaylightDate member of the TIME_ZONE_INFORMATION structure.

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

Remarks

All translations between UTC time and local time are based on the following formula:

UTC = local time + bias

The bias is the difference, in minutes, between UTC time and local time.

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, SetTimeZoneInformation, TIME_ZONE_INFORMATION


LocalFileTimeToFileTime

The LocalFileTimeToFileTime function converts a local file time to a file time based on the Coordinated Universal Time (UTC).

BOOL LocalFileTimeToFileTime(
  CONST FILETIME *lpLocalFileTime,  // local file time
  LPFILETIME lpFileTime             // file time
);

Parameters

lpLocalFileTime
[in] Pointer to a FILETIME structure that specifies the local file time to be converted into a UTC-based file time.
lpFileTime
[out] Pointer to a FILETIME structure to receive the converted UTC-based file time. This parameter cannot be the same as the lpLocalFileTime parameter.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, use the GetLastError function.

Remarks

LocalFileTimeToFileTime uses the current settings for the time zone and daylight saving time. Therefore, if it is daylight saving time, this function will take daylight saving time into account, even if the time you are converting is in standard time.

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, FILETIME, FileTimeToLocalFileTime


SetFileTime

The SetFileTime function sets the date and time that a file was created, last accessed, or last modified.

BOOL SetFileTime(
  HANDLE hFile,                     // handle to file
  CONST FILETIME *lpCreationTime,   // creation time
  CONST FILETIME *lpLastAccessTime, // last-access time
  CONST FILETIME *lpLastWriteTime   // last-write time
);

Parameters

hFile
[in] Handle to the file for which to set the dates and times. The file handle must have been created with GENERIC_WRITE access to the file.
lpCreationTime
[in] Pointer to a FILETIME structure that contains the date and time the file was created. This parameter can be NULL if the application does not need to set this information.
lpLastAccessTime
[in] Pointer to a FILETIME structure that contains the date and time the file was last accessed. The last access time includes the last time the file was written to, read from, or (in the case of executable files) run. This parameter can be NULL if the application does not need to set this information.
lpLastWriteTime
[in] Pointer to a FILETIME structure that contains the date and time the file was last written to. This parameter can be NULL if the application does not want to set this information.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on Windows NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Therefore, the GetFileTime function may not return the same file time information set using SetFileTime. Furthermore, FAT records times on disk in local time. However, NTFS records times on disk in UTC. For more information, see File Times.

For an example, see Changing a File Time to the Current Time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, File Times, FILETIME, GetFileSize, GetFileTime, GetFileType


SetLocalTime

The SetLocalTime function sets the current local time and date.

BOOL SetLocalTime(
  CONST SYSTEMTIME *lpSystemTime   // local time
);

Parameters

lpSystemTime
[in] Pointer to a SYSTEMTIME structure that contains the current local date and time.

The wDayOfWeek member of the SYSTEMTIME structure is ignored.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

Windows NT/2000 or later: The system uses UTC internally. Therefore, when you call SetLocalTime, the system uses the current time zone information to perform the conversion, including the daylight saving time setting. Note that the system uses the daylight saving time setting of the current time, not the new time you are setting. Therefore, to ensure the correct result, call SetLocalTime a second time, now that the first call has updated the daylight saving time setting.

Windows NT/2000 or later: The SetLocalTime function enables the SE_SYSTEMTIME_NAME privilege before changing the local time. This privilege is disabled by default. For more information about security privileges, see Privileges.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, AdjustTokenPrivileges, GetLocalTime, GetSystemTime, SetSystemTimeAdjustment, SYSTEMTIME


SetSystemTime

The SetSystemTime function sets the current system time and date. The system time is expressed in Coordinated Universal Time (UTC).

BOOL SetSystemTime(
  CONST SYSTEMTIME *lpSystemTime   // system time
);

Parameters

lpSystemTime
[in] Pointer to a SYSTEMTIME structure that contains the current system date and time.

The wDayOfWeek member of the SYSTEMTIME structure is ignored.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

Windows NT/2000 or later: The SetSystemTime function enables the SE_SYSTEMTIME_NAME privilege before changing the system time. This privilege is disabled by default. For more information about security privileges, see Privileges.

For an example, see Setting the System Time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, GetSystemTime, SetSystemTimeAdjustment, SYSTEMTIME


SetSystemTimeAdjustment

The SetSystemTimeAdjustment function enables or disables periodic time adjustments to the system's time-of-day clock. Such time adjustments are used to synchronize the time of day with some other source of time information. When periodic time adjustments are enabled, they are applied at each clock interrupt.

BOOL SetSystemTimeAdjustment(
  DWORD dwTimeAdjustment,       // size of adjustment
  BOOL bTimeAdjustmentDisabled  // disable option
);

Parameters

dwTimeAdjustment
[in] Specifies the number of 100-nanosecond units added to the time-of-day clock at each clock interrupt if periodic time adjustment is enabled.
bTimeAdjustmentDisabled
[in] Specifies the time adjustment mode that the system is to use. Periodic system time adjustments can be disabled or enabled.

A value of TRUE specifies that periodic time adjustment is to be disabled. The system is free to adjust time of day using its own internal mechanisms. The value of dwTimeAdjustment is ignored. The system's internal adjustment mechanisms may cause the time-of-day clock to jump noticeably when adjustments are made.

A value of FALSE specifies that periodic time adjustment is to be enabled, and will be used to adjust the time-of-day clock. The system will not interfere with the time adjustment scheme, and will not attempt to synchronize time of day on its own. The system will add the value of dwTimeAdjustment to the time of day at each clock interrupt.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError. One way the function can fail is if the caller does not possess the SE_SYSTEMTIME_NAME privilege.

Remarks

The GetSystemTimeAdjustment and SetSystemTimeAdjustment functions support algorithms that synchronize the time-of-day clock, reported via GetSystemTime and GetLocalTime, with another time source using a periodic time adjustment.

The SetSystemTimeAdjustment function supports two modes of time synchronization: time-adjustment – disabled and time-adjustment – enabled.

In the first mode, bTimeAdjustmentDisabled is set to FALSE. At each clock interrupt, the system adds the value of dwTimeAdjustment to the time of day. The clock interrupt rate may be determined by calling GetSystemTimeAdjustment, and looking at the returned value of the DWORD value pointed to by lpTimeIncrement.

In the second mode, bTimeAdjustmentDisabled is set to TRUE. At each clock interrupt, the system adds the interval between clock interrupts to the time of day. No adjustment to that interval is made. The system is free to periodically refresh the time-of-day clock using other techniques. Such other techniques may cause the time-of-day clock to jump noticeably when adjustments are made.

An application must have system-time privilege (the SE_SYSTEMTIME_NAME privilege) for this function to succeed. The SE_SYSTEMTIME_NAME privilege is disabled by default. Use the AdjustTokenPrivileges function to enable the privilege before calling SetSystemTimeAdjustment, and then to disable the privilege after the SetSystemTimeAdjustment call.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, AdjustTokenPrivileges, GetLocalTime, GetSystemTime, GetSystemTimeAdjustment


SetTimeZoneInformation

The SetTimeZoneInformation function sets the current time-zone parameters. These parameters control translations from Coordinated Universal Time (UTC) to local time.

BOOL SetTimeZoneInformation(
  CONST TIME_ZONE_INFORMATION *lpTimeZoneInformation
);

Parameters

lpTimeZoneInformation
[in] Pointer to a TIME_ZONE_INFORMATION structure that contains the time-zone parameters to set.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

All translations between UTC and local time are based on the following formula:

UTC = local time + bias

The bias is the difference, in minutes, between UTC and local time.

To disable the automatic adjustment for daylight saving time, use the following registry value:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\DisableAutoDaylightTimeSet

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, GetTimeZoneInformation, TIME_ZONE_INFORMATION


SystemTimeToFileTime

The SystemTimeToFileTime function converts a system time to a file time.

BOOL SystemTimeToFileTime(
  CONST SYSTEMTIME *lpSystemTime,  // system time
  LPFILETIME lpFileTime            // file time
);

Parameters

lpSystemTime
[in] Pointer to a SYSTEMTIME structure that contains the time to be converted.

The wDayOfWeek member of the SYSTEMTIME structure is ignored.

lpFileTime
[out] Pointer to a FILETIME structure to receive the converted system time.

Return Values

If the function succeeds, the return value is nonzero.

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

Remarks

MAPI: For more information, see Syntax and Limitations for Functions Useful in MAPI Development.

For an example, see Changing a File Time to the Current Time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, DosDateTimeToFileTime, FILETIME, FileTimeToDosDateTime, FileTimeToSystemTime, SYSTEMTIME


SystemTimeToTzSpecificLocalTime

The SystemTimeToTzSpecificLocalTime function converts a time in Coordinated Universal Time (UTC) to a specified time zone's corresponding local time.

BOOL SystemTimeToTzSpecificLocalTime(
  LPTIME_ZONE_INFORMATION lpTimeZone, // time zone
  LPSYSTEMTIME lpUniversalTime,       // universal time
  LPSYSTEMTIME lpLocalTime            // local time
);

Parameters

lpTimeZone
[in] Pointer to a TIME_ZONE_INFORMATION structure that specifies the time zone of interest.

If lpTimeZone is NULL, the function uses the currently active time zone.

lpUniversalTime
[in] Pointer to a SYSTEMTIME structure that specifies a UTC. The function converts this universal time to the specified time zone's corresponding local time.
lpLocalTime
[out] Pointer to a SYSTEMTIME structure that receives the local time information.

Return Values

If the function succeeds, the return value is nonzero, and the function sets the members of the SYSTEMTIME structure pointed to by lpLocalTime to the appropriate local time values.

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

Requirements

Windows NT/2000 or later: Requires Windows NT 3.5 or later.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, GetSystemTime, GetTimeZoneInformation, SYSTEMTIME, TIME_ZONE_INFORMATION, TzSpecificLocalTimeToSystemTime


TzSpecificLocalTimeToSystemTime

[This is preliminary documentation and subject to change.]

The TzSpecificLocalTimeToSystemTime function converts a local time to a time in Coordinated Universal Time (UTC).

BOOL TzSpecificLocalTimeToSystemTime(
  LPTIME_ZONE_INFORMATION lpTimeZoneInformation,
  LPSYSTEMTIME lpLocalTime,
  LPSYSTEMTIME lpUniversalTime
);

Parameters

lpTimeZoneInformation
[in] Pointer to a TIME_ZONE_INFORMATION structure that specifies the time zone for the time specified in lpLocalTime.
lpLocalTime
[in] Pointer to a SYSTEMTIME structure that specifies a local time. The function converts this time to the corresponding UTC time.
lpUniversalTime
[out] Pointer to a SYSTEMTIME structure that receives the UTC time.

Return Values

If the function succeeds, the return value is nonzero, and the function sets the members of the SYSTEMTIME structure pointed to by lpUniversalTime to the appropriate values.

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

Requirements

Windows NT/2000 or later: Requires Whistler.
Windows 95/98/Me: Unsupported.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.

See Also

Time Overview, Time Functions, GetSystemTime, GetTimeZoneInformation, SYSTEMTIME, SystemTimeToTzSpecificLocalTime, TIME_ZONE_INFORMATION


Time Structures

The following structures are used with time.

FILETIME
SYSTEMTIME
TIME_ZONE_INFORMATION


FILETIME

The FILETIME structure is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).

typedef struct _FILETIME {
    DWORD dwLowDateTime;
    DWORD dwHighDateTime;
} FILETIME, *PFILETIME;

Members

dwLowDateTime
Specifies the low-order 32 bits of the file time.
dwHighDateTime
Specifies the high-order 32 bits of the file time.

Remarks

To convert a FILETIME structure into a time that is easy to display to a user, use the FileTimeToSystemTime function.

It is not recommended that you add and subtract values from the FILETIME structure to obtain relative times. Instead, you should

  • Copy the resulting FILETIME structure to a ULARGE_INTEGER structure.
  • Use normal 64-bit arithmetic on the ULARGE_INTEGER value.

Not all file systems can record creation and last access time and not all file systems record them in the same manner. For example, on NT FAT, create time has a resolution of 10 milliseconds, write time has a resolution of 2 seconds, and access time has a resolution of 1 day (really, the access date). On NTFS, access time has a resolution of 1 hour. Therefore, the GetFileTime function may not return the same file time information set using the SetFileTime function. Furthermore, FAT records times on disk in local time. However, NTFS records times on disk in UTC. For more information, see File Times.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Time Overview, Time Structures, File Times, CompareFileTime, FileTimeToSystemTime GetFileTime, ULARGE_INTEGER


SYSTEMTIME

The SYSTEMTIME structure represents a date and time using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.

typedef struct _SYSTEMTIME {
    WORD wYear;
    WORD wMonth;
    WORD wDayOfWeek;
    WORD wDay;
    WORD wHour;
    WORD wMinute;
    WORD wSecond;
    WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;

Members

wYear
Specifies the current year.
wMonth
Specifies the current month; January = 1, February = 2, and so on.
wDayOfWeek
Specifies the current day of the week; Sunday = 0, Monday = 1, and so on.
wDay
Specifies the current day of the month.
wHour
Specifies the current hour.
wMinute
Specifies the current minute.
wSecond
Specifies the current second.
wMilliseconds
Specifies the current millisecond.

Remarks

It is not recommended that you add and subtract values from the SYSTEMTIME structure to obtain relative times. Instead, you should

  • Convert the SYSTEMTIME structure to a FILETIME structure.
  • Copy the resulting FILETIME structure to a ULARGE_INTEGER structure.
  • Use normal 64-bit arithmetic on the ULARGE_INTEGER value.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Time Overview, Time Structures, FILETIME, GetSystemTime, ULARGE_INTEGER, SetSystemTime


TIME_ZONE_INFORMATION

The TIME_ZONE_INFORMATION structure specifies information specific to the time zone.

typedef struct _TIME_ZONE_INFORMATION {
    LONG       Bias;
    WCHAR      StandardName[ 32 ];
    SYSTEMTIME StandardDate;
    LONG       StandardBias;
    WCHAR      DaylightName[ 32 ];
    SYSTEMTIME DaylightDate;
    LONG       DaylightBias;
} TIME_ZONE_INFORMATION, *PTIME_ZONE_INFORMATION;

Members

Bias
Specifies the current bias, in minutes, for local time translation on this computer. The bias is the difference, in minutes, between Coordinated Universal Time (UTC) and local time. All translations between UTC and local time are based on the following formula:
UTC = local time + bias

This member is required.

StandardName
Specifies a null-terminated string associated with standard time on this operating system. For example, this member could contain "EST" to indicate Eastern Standard Time. This string is not used by the operating system, so anything stored there using the SetTimeZoneInformation function is returned unchanged by the GetTimeZoneInformation function. This string can be empty.
StandardDate
Specifies a SYSTEMTIME structure that contains a date and local time when the transition from daylight saving time to standard time occurs on this operating system. If this date is not specified, the wMonth member in the SYSTEMTIME structure must be zero. If this date is specified, the DaylightDate value in the TIME_ZONE_INFORMATION structure must also be specified.

To select the correct day in the month, set the wYear member to zero, the wDayOfWeek member to an appropriate weekday, and the wDay member to a value in the range 1 through 5. Using this notation, the first Sunday in April can be specified, as can the last Thursday in October (5 is equal to "the last").

StandardBias
Specifies a bias value to be used during local time translations that occur during standard time. This member is ignored if a value for the StandardDate member is not supplied.

This value is added to the value of the Bias member to form the bias used during standard time. In most time zones, the value of this member is zero.

DaylightName
Specifies a null-terminated string associated with daylight saving time on this operating system. For example, this member could contain "PDT" to indicate Pacific Daylight Time. This string is not used by the operating system, so anything stored there by using the SetTimeZoneInformation function is returned unchanged by the GetTimeZoneInformation function. This string can be empty.
DaylightDate
Specifies a SYSTEMTIME structure that contains a date and local time when the transition from standard time to daylight saving time occurs on this operating system. If this date is not specified, the wMonth member in the SYSTEMTIME structure must be zero. If this date is specified, the StandardDate value in the TIME_ZONE_INFORMATION structure must also be specified.

To select the correct day in the month, set the wYear member to zero, the wDayOfWeek member to an appropriate weekday, and the wDay member to a value in the range 1 through 5. Using this notation, the first Sunday in April can be specified, as can the last Thursday in October (5 is equal to "the last").

DaylightBias
Specifies a bias value to be used during local time translations that occur during daylight saving time. This member is ignored if a value for the DaylightDate member is not supplied.

This value is added to the value of the Bias member to form the bias used during daylight saving time. In most time zones, the value of this member is – 60.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winbase.h; include Windows.h.

See Also

Time Overview, Time Structures, GetTimeZoneInformation, SetTimeZoneInformation, SYSTEMTIME


Time Messages

The following message is used with time.

WM_TIMECHANGE


WM_TIMECHANGE

An application sends the WM_TIMECHANGE message whenever it updates the system time.

To send this message, call the SendMessage function with the following parameters.

SendMessage(
  (HWND) hWnd,              // handle to destination window
  WM_TIMECHANGE,            // message to send
  (WPARAM) wParam,          // not used; must be zero
  (LPARAM) lParam          // not used; must be zero
);

Parameters

This message has no parameters.

Return Values

An application should return zero if it processes this message.

Remarks

To send this message to all top-level windows, an application can use the SendMessage function with the hWnd parameter set to HWND_TOPMOST.

Windows 2000 and later: An application should not broadcast this message, because the system will broadcast this message when the application changes the system time.

Windows NT 4.0 and earlier: An application should send this message to all top-level windows after changing the system time.

Windows 95/98/Me: An application should send this message to all top-level windows after changing the system time.

Requirements

Windows NT/2000 or later: Requires Windows NT 3.1 or later.
Windows 95/98/Me: Requires Windows 95 or later.
Header: Declared in Winuser.h; include Windows.h.

See Also

Time Overview, Time Messages, SendMessage


Time Provider

[This is preliminary documentation and subject to change.]

Whistler provides support for a variety of hardware devices and network time protocols using the time provider architecture. Input time providers retrieve accurate time stamps from hardware or the network, and output time providers provide time stamps to other clients on the network.

Time providers are managed by the time provider manager. It is responsible for loading, starting, and stopping time providers as directed by the service control manager. This interface makes writing a time provider easier than writing a full Win32 service.

  • Creating a Time Provider
  • Registering a Time Provider
  • Sample Time Provider


Creating a Time Provider

[This is preliminary documentation and subject to change.]

A time provider is implemented as a DLL. Each DLL can support multiple time providers. Each provider is responsible for its own configuration and synchronization.

Time providers must implement the following callback functions:

  • TimeProvClose
  • TimeProvCommand
  • TimeProvOpen

After it has loaded the provider DLL, the time provider manager calls TimeProvOpen, passing the name of the provider and pointers to the following functions:

  • AlertSamplesAvail
  • GetTimeSysInfo
  • LogTimeProvEvent

These functions are for use by the time provider. The time provider uses TimeProvOpen to return a provider handle that the time provider manager uses when sending commands to the time provider. The handle value is defined by the time provider and is used primarily to distinguish between different providers implemented in the same DLL. The time provider can log significant events using LogTimeProvEvent.

The time provider manager uses TimeProvCommand to send commands to the time provider. When the time provider needs to notify the time provider manager that it has time samples available, it calls AlertSamplesAvail. The time provider manager then calls TimeProvCommand with the TPC_GetSamples command to retrieve the time samples. It can take up to 16 seconds for the time provider manager to request the sample. Therefore, the application should not wait for the request.

To ensure accuracy, the time provider should retrieve all time-related information using GetTimeSysInfo.

When it is time to shut down the time provider, the time provider manager calls TimeProvClose.


Registering a Time Provider

[This is preliminary documentation and subject to change.]

The system loads a time provider based on its configuration information stored in the registry. Each time provider should create the following registry key:

HKEY_LOCAL_MACHINE
System\
CurrentControlSet\
Services\
W32Time\
TimeProviders
 ProviderName

The following table describes the values that must exist in each provider's key.

Value | Description
DllName | The name of the DLL that contains the provider. This value has the type REG_SZ.
Enabled | Indicates whether the provider should be started. If this value is 1, the provider is started. Otherwise, the provider is not started. This value has the type REG_DWORD.
InputProvider | Indicates whether the provider is an input provider or an output provider. If this value is 1, the provider is an input provider. Otherwise, the provider is an output provider. This value has the type REG_DWORD.

The time provider manager enumerates the keys under the TimeProviders key and starts each enabled provider. Providers are started at system startup and whenever there are parameter changes.

Each time provider can also store application-specific configuration information in the registry.


Sample Time Provider

[This is preliminary documentation and subject to change.]

The following example demonstrates how to structure a time provider. In this example, the DLL supports two hardware time providers.

#include <windows.h>
#include "timeprov.h"

// Global variables.
TimeProvSysCallbacks sc;
WCHAR ProviderName1[] = L"MyCompanyMyAppProvider1";
WCHAR ProviderName2[] = L"MyCompanyMyAppProvider2";
const TimeProvHandle htp1 = (TimeProvHandle)1;
const TimeProvHandle htp2 = (TimeProvHandle)2;

// Stores the current set of best samples.
TpcGetSamplesArgs Samples;

// Stores the polling interval the system requires to maintain clock
// stability. The provider need not poll more often.
DWORD dwPollInterval;

HRESULT CALLBACK TimeProvOpen(
   WCHAR *wszName,
   TimeProvSysCallbacks *pSysCallbacks,
   TimeProvHandle *phTimeProv)
{
   // Spawn a thread to read configuration information from the
   // registry.
   ;

   // Copy the system callback pointers to a buffer.
   CopyMemory(&sc, (PVOID)pSysCallbacks, sizeof(TimeProvSysCallbacks));

   // Return the handle to the appropriate time provider.
   if ( lstrcmp(wszName, ProviderName1) == 0 )
      *phTimeProv = htp1;
   else *phTimeProv = htp2;

   return S_OK;
}

HRESULT CALLBACK TimeProvCommand(
   TimeProvHandle hTimeProv,
   TimeProvCmd eCmd,
   PVOID pvArgs)
{
   switch( eCmd )
   {
      case TPC_GetSamples:
      // Return the Samples structure in pvArgs.
         CopyMemory(pvArgs, &Samples, sizeof(TpcGetSamplesArgs));
         break;
      case TPC_PollIntervalChanged:
      // Retrieve the new value.
         GetTimeSysInfo( TSI_PollInterval, &dwPollInterval );
         break;
      case TPC_TimeJumped:
      // Discard samples saved in the Samples structure.
         ZeroMemory(&Samples, sizeof(TpcGetSamplesArgs));
         break;
      case TPC_UpdateConfig:
      // Read the configuration information from the registry.
         break;
   }
   return S_OK;
}

HRESULT CALLBACK TimeProvClose(
   TimeProvHandle hTimeProv)
{
   if( hTimeProv == htp1 )
   {
   // Terminate MyCompanyMyAppProvider1, performing any cleanup.
   ;
   }
   else
   {
   // Terminate MyCompanyMyAppProvider2, performing any cleanup.
   ;
   }

   return S_OK;
}


Time Provider Reference

[This is preliminary documentation and subject to change.]

The following elements are used by time providers:

  • Time Provider Functions
  • Time Provider Structures


Time Provider Functions

[This is preliminary documentation and subject to change.]

The following functions are used by time providers.

Function | Description
AlertSamplesAvail | Notifies the system that there are new samples available.
GetTimeSysInfo | Retrieves system state information.
LogTimeProvEvent | Logs an event.
TimeProvClose | Called by the time provider manager to shut down the time provider.
TimeProvCommand | Called by the time provider manager to send commands to the time provider.
TimeProvOpen | Called by the time provider manager when the time provider DLL is loaded.


AlertSamplesAvail

[This is preliminary documentation and subject to change.]

The AlertSamplesAvail function notifies the system that there are new time samples available.

HRESULT CALLBACK AlertSamplesAvailFunc(void);

Parameters

This function has no parameters.

Return Value

If the function succeeds, the return value is S_OK. Otherwise, the return value is one of the error codes defined in WinError.h.

Remarks

The time provider manager uses this notification to determine when to send a TPC_GetSamples command. A hardware provider does not need to call this function, as the time provider manager requests samples without this notification. Time providers that provide samples sporadically, such as a provider that works in the background when a user establishes a transient dial-up connection, must call this function.

The TimeProvOpen function returns a pointer to this function.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

TimeProvOpen


GetTimeSysInfo

[This is preliminary documentation and subject to change.]

The GetTimeSysInfo function retrieves system state information.

HRESULT CALLBACK GetTimeSysInfoFunc(
  TimeSysInfo eInfo,
  PVOID pvInfo
);

Parameters

eInfo
[in] Specifies the requested state information. This parameter can be one of the following values.
Value | Meaning
TSI_ClockPrecision | The pvInfo parameter is a signed __int32 value that specifies the clock precision, in log2(s).
TSI_ClockTickSize | The pvInfo parameter is an unsigned __int64 value that specifies the clock tick size, in (10^-7)s.
TSI_CurrentTime | The pvInfo parameter is an unsigned __int64 value that specifies the current time, in (10^-7)s.
TSI_LastSyncTime | The pvInfo parameter is an unsigned __int64 value that specifies the last synch time, in (10^-7)s.
TSI_LeapFlags The pvInfo parameter is a BYTE value that indicates an impending leap second or loss of synchronization. The following values are defined:

0 No change.
1 Add leap second.
2 Subtract leap second.
3 Not synchronized.
TSI_PhaseOffset | The pvInfo parameter is a signed __int64 value that specifies the phase offset.
TSI_PollInterval | The pvInfo parameter is a signed __int32 value that specifies the poll interval, in log2(s).
TSI_ReferenceIdentifier | The pvInfo parameter is a DWORD value that specifies the reference identifier for the time source, in NTP format (either an IP address or a four character ASCII string that describes the hardware source, such as Global Positioning System (GPS) or WWVB)..
TSI_RootDelay | The pvInfo parameter is a signed __int64 value that specifies the root delay, in (10^-7)s.
TSI_RootDispersion | The pvInfo parameter is an unsigned __int64 value that specifies, the root dispersion, in (10^-7)s.
TSI_Stratum | The pvInfo parameter is a BYTE value that specifies the number of network hops separate this computer from the root source. Hardware providers should return zero. NTP providers should return the stratum of the peer that provided the sample.
TSI_TickCount | The pvInfo parameter is an unsigned __int64 value that specifies the tick count. This value will eventually wrap, so it should be used only to compare short intervals.
TSI_TSFlags The pvInfo parameter is a DWORD value that specifies one of the following time source flags:

TSF_Authenticated
TSF_Hardware

pvInfo
[out] Pointer to a buffer that receives that state information. The format of this data depends on the value of eInfo.

Return Value

If the function succeeds, the return value is S_OK. Otherwise, the return value is one of the error codes defined in WinError.h.

Remarks

To ensure accuracy, the time provider should retrieve all time-related information using GetTimeSysInfo. Note that the time values should not be used directly in an NTP packet. They are expressed relative to 12:00 A.M. January 1, 1601, whereas NTP specifies that time values be expressed relative to 12:00 A.M. January 1, 1900.

The TimeProvOpen function returns a pointer to this function.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

TimeProvOpen


LogTimeProvEvent

[This is preliminary documentation and subject to change.]

The LogTimeProvEvent function logs an event in the event log.

HRESULT LogTimeProvEventFunc(
  WORD wType,
  WCHAR * wszProvName,
  WCHAR * wszMessage
);

Parameters

wType
[in] Specifies the event type. This parameter can be one of the following values.
Value | Meaning
Error | Indicates a significant problem.
Information | Provides information about a successful operation.
Warning | Indicates a problem that is not immediately significant, but may cause future problems.

wszProvName
[in] Pointer to a string that specifies the provider name.
wszMessage
[in] Pointer to a string that describes the event.

Return Value

If the function succeeds, the return value is S_OK. Otherwise, the return value is one of the error codes defined in WinError.h.

Remarks

This function provides the time provider with a simplified interface for event logging. Time providers that require more extensive event logging can perform their own event logging. For more information on event logging, see Event Logging.

The TimeProvOpen function returns a pointer to this function.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

TimeProvOpen


TimeProvClose

[This is preliminary documentation and subject to change.]

The TimeProvClose callback function is called by the time provider manager to shut down the time provider.

HRESULT CALLBACK TimeProvClose(
  TimeProvHandle hTimeProv
);

Parameters

hTimeProv
[in] Handle to the time provider. The TimeProvOpen function receives this handle.

Return Value

If the function succeeds, the return value is S_OK. Otherwise, the return value is one of the error codes defined in WinError.h.

Remarks

The provider should clean up its resources and terminate its operation. When the function returns, the time provider manager can unload the DLL. Therefore, the handle to the time provider is no longer valid and should not be used again.

For an example, see Sample Time Provider.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

TimeProvOpen


TimeProvCommand

[This is preliminary documentation and subject to change.]

The TimeProvCommand callback function is called by the time provider manager to send commands to the time provider.

HRESULT CALLBACK TimeProvCommand(
  TimeProvHandle hTimeProv,
  TimeProvCmd eCmd,
  PVOID pvArgs
);

Parameters

hTimeProv
[in] Handle to the time provider. The TimeProvOpen function receives this handle.
eCmd
[in] Specifies the command. This parameter can be one of the following values.
Command Description
TPC_GetSamples The time provider should return the time samples it has collected. If there is no data available, the provider should return no samples. For more details, see Remarks.

The pvArgs parameter is pointer to a TpcGetSamplesArgs structure. The time provider manager provides the buffer for the samples. If the pvArgs buffer if too small, the provider should provide as many samples as is can and return ERROR_INSUFFICIENT_BUFFER. Any other error codes returned by the provider are ignored.
TPC_NetTopoChange The network topology has changed. Network providers must redetect the network settings and verify that they can reach their sources.

The pvArgs parameter is not used. Any error returned by the provider is ignored.
TPC_PollIntervalChanged The polling interval has changed. The time provider should call the GetTimeSysInfo function to retrieve the new value.

The pvArgs parameter is not used. Any error returned by the provider is ignored.
TPC_TimeJumped The system clock was adjusted abruptly, so the time provider should discard any time stamps it has saved.

The pvArgs parameter is not used. Any error returned by the provider is ignored.
TPC_UpdateConfig The time provider should verify whether its application-specific configuration data stored in the registry has changed.

The pvArgs parameter is not used. Any error returned by the provider is ignored.

pvArgs
[in] Pointer to a buffer that specifies command information. The format of this data depends on the value of eCmd.

Return Value

If the function succeeds, the return value is S_OK. Otherwise, the return value is one of the error codes defined in WinError.h.

Remarks

The time provider should never take longer than half a second to return from this call.

When processing the TPC_GetSamples command, the provider should return one sample for each source it is monitoring. Therefore, a hardware provider should return one sample, while a network provider like NTP can return multiple samples. The provider should not return multiple samples from a single source; it should return the best sample from its cache of samples for the source. The provider can return the same sample on subsequent calls, provided that the data has not changed.

For an example, see Sample Time Provider.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

GetTimeSysInfo, TpcGetSamplesArgs, TimeProvOpen


TimeProvOpen

[This is preliminary documentation and subject to change.]

The TimeProvOpen callback function is called by the time provider manager when the time provider DLL is loaded.

HRESULT CALLBACK TimeProvOpen(
  WCHAR * wszName,
  TimeProvSysCallbacks * pSysCallbacks,
  TimeProvHandle * phTimeProv
);

Parameters

wszName
[in] Specifies the provider name.
pSysCallbacks
[in] Pointer to a TimeProvSysCallbacks structure that specifies pointers to the functions provided by the time service to the time provider. The system allocates this structure, and it is destroyed when the function returns. Therefore, you must copy the information to another buffer.
phTimeProv
[out] Pointer to a buffer that contains a handle to the provider. The time provider manager uses this handle to communicate with the time provider.

Return Value

If the function succeeds, the return value is S_OK. Otherwise, the return value is one of the error codes defined in WinError.h.

Remarks

You should return from this callback function as quickly as possible. Perform any initialization in another thread.

For an example, see Sample Time Provider.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

AlertSamplesAvail, GetTimeSysInfo, LogTimeProvEvent, TimeProvSysCallbacks


Time Provider Structures

[This is preliminary documentation and subject to change.]

The following structures are used with time providers:

TpcGetSamplesArgs
TimeProvSysCallbacks
TimeSample


TpcGetSamplesArgs

[This is preliminary documentation and subject to change.]

The TpcGetSamplesArgs structure is used by the TimeProvCommand function.

typedef struct TpcGetSamplesArgs {
    BYTE *pbSampleBuf;
    DWORD cbSampleBuf;
    DWORD dwSamplesReturned;
    DWORD dwSamplesAvailable;
} TpcGetSamplesArgs;

Members

pbSampleBuf
An array of TimeSample structures.
cbSampleBuf
Size of pbSampleBuf, in bytes.
dwSamplesReturned
Number of samples returned.
dwSamplesAvailable
Total number of samples available.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

TimeProvCommand, TimeSample


TimeProvSysCallbacks

[This is preliminary documentation and subject to change.]

The TimeProvSysCallbacks structure contains pointers to functions for use by the time provider.

typedef struct TimeProvSysCallbacks {
    DWORD dwSize;
    GetTimeSysInfoFunc * pfnGetTimeSysInfo;
    LogTimeProvEventFunc * pfnLogTimeProvEvent;
    AlertSamplesAvailFunc * pfnAlertSamplesAvail;
} TimeProvSysCallbacks;

Members

dwSize
Specifies the size of the structure, in bytes.
pfnGetTimeSysInfo
Pointer to the GetTimeSysInfo function.
pfnLogTimeProvEvent
Pointer to the LogTimeProvEvent function.
pfnAlertSamplesAvail
Pointer to the AlertSamplesAvail function.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

TimeProvOpen


TimeSample

[This is preliminary documentation and subject to change.]

The TimeSample structure represents a time sample.

typedef struct TimeSample {
    DWORD dwSize;
    DWORD dwRefid;
    signed __int64 toOffset;
    signed __int64 toDelay;
    unsigned __int64 tpDispersion;
    unsigned __int64 nSysTickCount;
    signed __int64 nSysPhaseOffset;
    BYTE nLeapFlags;
    BYTE nStratum;
    DWORD dwTSFlags;
    WCHAR wszUniqueName[256];
} TimeSample;

Members

dwSize
Size of the structure, in bytes.
dwRefid
Reference identifier for the time source, in NTP format (either an IP address or a four character ASCII string that describes the hardware source, such as GPS or WWVB).
toOffset
Difference between local and remote clocks, in (10^-7)s.
toDelay
Total roundtrip delay, in (10^-7)s. This is the time packets spent in transit from the root time source to the client, including root delay. For NTP providers, this means roundtrip delay to the peer, plus the peer's root delay. The hardware providers, this value is probably zero.
tpDispersion
Total measurement error of the clock offset, including root dispersion, in (10^-7)s. This includes errors in reading the local clock, uncertainty in the local clock frequency, and error from filters. For NTP providers, this includes the peer's root dispersion.
nSysTickCount
Returned by GetTimeSysInfo with TSI_TickCount.
nSysPhaseOffset
Returned by GetTimeSysInfo with TSI_PhaseOffset.
nLeapFlags
Indicates an impending leap second or loss of synchronization. This member can be one of the following values:
Value | Meaning
0 | No change.
1 | Add leap second.
2 | Subtract leap second.
3 | Not synchronized.

nStratum
Number of network hops separating this computer from the root source. Hardware providers should return zero. NTP providers should return the stratum of the peer that provided the sample.
dwTSFlags
Information about the time source.
Value | Meaning
TSF_Authenticated | The sample has been cryptographically authenticated.
TSF_Hardware | The sample is from a hardware device such as a GPS or radio receiver.

wszUniqueName
Name that uniquely identifies the source of the sample. For network providers, the name should include the protocol and IP addresses. For hardware devices, the name should include the device name and communication port.

Requirements

Windows NT/2000 or later: Requires Whistler.
Header: Declared in Timeprov.h.

See Also

GetTimeSysInfo, TpcGetSamplesArgs


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.