DirectX SDK

Using Flags

[C++]

This topic pertains only to applications written in Visual Basic.

[Visual Basic]

Many object methods in DirectX for Visual Basic take a flags parameter, or a parameter with a similar name. Also, some types have a member containing flags. Flags are used to control miscellaneous aspects of the behavior of method calls or to report details about things like device capabilities.

A flag is a single bit of information. It dictates or reports whether a certain behavior or capability is present or absent. A set of related flags is represented by an enumeration whose members generally do not share any bits. (Some flags, however, may represent combinations of other flags.)

Because flags represent single bits, multiple flags can be combined in a single value. For example, suppose you wanted to set the cooperative level of a DirectInput device to both foreground and exclusive. You would do so by combining two flags, using a logical Or operation, as follows:

' diDevice is a DirectInputDevice object, and hwnd is a window handle
diDevice.SetCooperativeLevel(hwnd, _
    DISCL_FOREGROUND Or DISCL_EXCLUSIVE)

In most cases, combining two or more flags by using the Or operator is equivalent to summing them by using the addition operator. However, it is unwise to add flags together, because of the fact that some flags do represent combinations of bits. In the following hypothetical example, the flag CF_PURPLE represents a combination of CF_RED and CF_BLUE.

Enum COLORFLAGS
    CF_RED    = 1
    CF_BLUE   = 2
    CF_PURPLE = 3
    CF_GREEN  = 4
End Enum
 
Dim Color As Integer
Color = CF_RED Or CF_PURPLE

The value of Color is now 3. CF_RED is redundant, because CF_PURPLE already contains that value.

The following operation, on the other hand, sets an incorrect value:

' This is wrong!
Color = CF_RED + CF_PURPLE

The variable is now set to 4, which is equivalent to CF_GREEN.

When you retrieve a value for flags, you can extract the setting of an individual flag by using a logical And operation. If the flags value contains the bit represented by a flag constant, the And operation returns a nonzero value and that flag is "on". If the And operation returns zero, the flag is "off". For example, the following call determines whether an input device, whose capabilities have been retrieved in a variable of type DIDEVCAPS, is physically attached to the system:

Dim IsAttached As Boolean
IsAttached = diDevCaps.lFlags And DIDC_ATTACHED 

Note that you should not test for equality, as in the following example:

' This is wrong!
IsAttached = (diDevCaps.lFlags = DIDC_ATTACHED)

The reason this won't work is that the value in lFlags might contain other bits as well, such as DIDC_FORCEFEEDBACK. (See CONST_DIDEVCAPSFLAGS.)