Platform SDK: DirectX |
The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.
DirectInput provides the IDirectInputDevice7::Acquire and IDirectInputDevice7::Unacquire methods to manage device access. Your application must call the Acquire method to gain access to the device before requesting mouse information with the IDirectInputDevice7::GetDeviceState and IDirectInputDevice7::GetDeviceData methods.
Most of the time your application will have the device acquired. However, if you have only foreground access the mouse will automatically be unacquired whenever your application moves to the background. You are responsible for reacquiring it when you get the focus back again. This can be done in response to a WM_ACTIVATE message.
Scrawl handles this message by setting a global variable, g_fActive, according to whether the application is gaining or losing the focus. It then calls a helper function, Scrawl_SyncAcquire, which acquires the mouse if g_fActive is TRUE and unacquires it otherwise.
case WM_ACTIVATE: g_fActive = wParam == WA_ACTIVE || wParam == WA_CLICKACTIVE; Scrawl_SyncAcquire(hwnd); break;
If you have exclusive access, your application may need to let go of the mouse to let the user interact with Windows—for example, to access a menu or a dialog box. In Scrawl this can happen when the user opens the system menu with ALT+SPACEBAR.
The Scrawl window procedure has a handler for WM_ENTERMENULOOP that responds by setting the global variable g_fActive to FALSE and calling the Scrawl_SyncAcquire function. This handler allows Windows to have the mouse and display its own cursor.
When the user is done using a menu, Windows sends the application a WM_EXITMENULOOP message. In this case, the Scrawl window process posts an application-defined message, WM_SYNCACQUIRE, to its own message queue. This allows other pending messages to be processed before the mouse is reacquired with the Scrawl_SyncAcquire function.
Scrawl also unacquires the mouse in response to a right button click, which opens up a context menu. Although the mouse would get unacquired later, in the WM_ENTERMENULOOP handler, it's done here first so that the position of the Windows cursor can be set before the menu appears.
Finally, Scrawl tries to reacquire the mouse if it receives a DIERR_INPUTLOST error after an attempt to retrieve data. This is just in case the device has been unacquired by some mechanism not covered elsewhere; for instance, if the user has pressed CTRL+ALT+DEL.
In summary, your application needs to acquire the mouse before it can get data from it. This needs to be done only once, as long as nothing happens to force your application to give up access to it. In exclusive mode, you are responsible for giving up control of the mouse when Windows needs it. You are also responsible for reacquiring the mouse whenever your program needs access to it after losing it to Windows or another application.