DirectX SDK |
This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.
Because there is no system joystick, in the sense that there can be a system keyboard or mouse, in order to create a DirectInputDevice object for a joystick you first need to obtain an instance GUID, or globally unique identifier. Generally this is done by enumerating the available joysticks, presenting the user with a choice, and then obtaining the information for the selected device.
The following function initializes DirectInput and enumerates attached joysticks:
Dim dx As New DirectX7 Dim di As DirectInput Dim diDev As DirectInputDevice Dim diDevEnum As DirectInputEnumDevices Sub InitDirectInput() On Error GoTo Error_Out Set di = dx.DirectInputCreate() Set diDevEnum = di.GetDIEnumDevices( _ DIDEVTYPE_JOYSTICK, DIEDFL_ATTACHEDONLY) If diDevEnum.GetCount = 0 Then MsgBox "No joystick attached." Unload Me End If 'Add attached joysticks to the listbox Dim i As Integer For i = 1 To diDevEnum.GetCount Call lstJoySticks.AddItem( _ diDevEnum.GetItem(i).GetInstanceName) Next ' Get an event handle to associate with the device EventHandle = dx.CreateEvent(Me) Exit Sub Error_Out: MsgBox "Error initializing DirectInput." Unload Me End Sub
When the user selects a joystick from the list, the device is created and initialized in the lstJoySticks_Click procedure:
Set diDev = di.CreateDevice(diDevEnum.GetItem( _ lstJoySticks.ListIndex + 1).GetGuidInstance) diDev.SetCommonDataFormat DIFORMAT_JOYSTICK diDev.SetCooperativeLevel Me.hWnd, _ DISCL_FOREGROUND Or DISCL_NONEXCLUSIVE
The call to DirectInput.CreateDevice takes as its parameter the GUID for a DirectInputDeviceInstance object obtained from the enumeration. Note that like all enumerated collections in DirectX for Visual Basic, the device enumeration is 1-based, so the index is one greater than the index of the selected item in the list box. The list box must also be unsorted.
You must set the data format before attempting to enumerate objects on the device or manipulate its properties.