Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2006.01.01;
Скачать: CL | DM;

Вниз

DirectInput8   Найти похожие ветки 

 
ink   (2005-07-28 22:34) [0]

Как можно узнать отпущена/нажата ли например - левая кнопка мыши?
DirectInput8.


 
Fosgen   (2005-07-28 22:43) [1]

Лезь на http://www.gamedev.ru/articles/ - там точно есть описание работы с DInput - сам оттуда статьи качал.


 
Sphinx ©   (2005-07-29 11:09) [2]

Поищи в сети книгу Краснова про DirectX - там подробно описана работа DirectInput


 
Мелкий ©   (2005-07-29 21:00) [3]


> ink   (28.07.05 22:34)  
> Как можно узнать отпущена/нажата ли например - левая кнопка
> мыши?
> DirectInput8.


А на чём пишешь? Если C++, то я буквально несколько дней назад тоже над вводом парился. Вроде всё понял, так что могу помочь, по мере сил конечно.


 
Sphinx ©   (2005-07-29 22:02) [4]

{==============================================================================
|                                                                            |
| оболочка над DirectInput позволяющая обеспечить быстрый доступ к           |
| мышке и клавиатуре в любых приложениях                                     |
|                                                                            |
==============================================================================}

unit uTDIControls;

interface

{==============================================================================
 подключаемые модули
==============================================================================}

uses
 Windows, DirectInput, uGameTypes, uGameConst;

{==============================================================================
 константы модуля
==============================================================================}

const
 { признак нажатой или отжатой клавиши }
 Key_Is_Down   = $80;
 Key_Is_Up     = 0;

type
 { класс контроллера - оболочки для DirectInput }
 TDIController = class (TObject)
   private
     // дополнительные данные класса
     FappWindowHandle          : THandle;              // указатель на ассоциированное окно

     // переменные зоны ограничения мыши
     FBoundsSet                : Boolean;              // признак ограничения движения мыши
     FBoundsLeft,                                      // размеры
     FBoundsTop,                                       //   области ограничений
     FBoundsWidth,                                     //   движения
     FBoundsHeight             : Integer;              //   мыши

     // основной интерфейс DirectInput
     FDirectInput8             : IDirectInput8;        // основной интерфейс DI
     FDirectInputAcquire       : Boolean;              // признак захвата интерфейса

     // мышь
     FDirectInputMouse         : IDirectInputDevice8;  // интерфейс устройства
     FDirectInputMouseAcquire  : Boolean;              // признак захвата мыши
     FMouseX,                                          // координаты мыши
     FMouseY,                                          //   X и Y - координаты курсора на экране
     FMouseZ                   : Integer;              //   Z - координата связанная с колесом мыши
     FMouseDX,                                         // приращения координат
     FMouseDY,                                         //   на предыдущем опросе
     FMouseDZ                  : Integer;              //
     FKMouseMove               : Single;               // коэф. влияющий на величину смещения мыши
     FDirectInputMouseKeyStat  : TMouseKeyStat;        // массив состояний клавишь

     // клавиатура
     FDirectInputKeyb          : IDirectInputDevice8;  // интерфейс устройства
     FDirectInputKeybAcquire   : Boolean;              // признак захвата клавиатуры
     FDirectInputKeybKeyStat   : TKeyboardStat;        // массив состояний кнопок

   protected
     FHRErrorCode              : HResult;              // переменная результатов

     procedure UpdateMouseData;
     procedure UpdateKeybData;
     function ResetKeybKey: TKeyboardStat;

     function GetMouseKeys: TMouseKeyStat;
     function GetKeybKeys: TKeyboardStat;

   public
     constructor Create(iHandle: THandle);
     destructor Destroy; override;

     property CurrentError: HResult read FHRErrorCode;

     property DirectInputAcquire: Boolean read FDirectInputAcquire;
     property DirectInputMouseAcquire: Boolean read FDirectInputMouseAcquire;
     property MouseX: Integer read FMouseX;
     property MouseY: Integer read FMouseY;
     property MouseZ: Integer read FMouseZ;
     property LastMouseDX: Integer read FMouseDX;
     property LastMouseDY: Integer read FMouseDY;
     property LastMouseDZ: Integer read FMouseDZ;
     property DirectInputKeyboardAcquire: Boolean read FDirectInputKeybAcquire;
     property MouseKeysStats: TMouseKeyStat read GetMouseKeys;
     property KeyboardKeysStats: TKeyboardStat read GetKeybKeys;

     procedure Update;
     function AcquireDirectInput: HResult;
     function AcquireMouse(startX, startY, startZ: Integer; KMove: Single): HResult;
     function UnAcquireMouse: HResult;
     procedure ResetMouseKey;
     procedure SetMouseBound(aLeft, aTop, aWidth, aHeight: Integer);
     procedure UnSetMouseBound;
     procedure SetMouseTo(iX, iY, iZ: Integer);
     function AcquireKeyboard: HResult;
     function UnAcquireKeyboard: HResult;
     procedure ResetKeyboardKey;
 end;

implementation

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                              FUNCTION                                      //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

{==============================================================================
==============================================================================}

function KeyIsDown(aKey: WORD): Boolean;
begin
 if (aKey and Key_Is_Down) = Key_Is_Down then
   Result := True
 else
   Result := False;
end;


 
Sphinx ©   (2005-07-29 22:03) [5]

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                            TDIController                                   //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

{==============================================================================
 конструктор класса

 ===== входные величины =====
 iHandle:      указатель на окно, ассоциируемое с DirectInputDevice
==============================================================================}

constructor TDIController.Create(iHandle: THandle);
begin
 // проверка и защита от повторного создания
 if Assigned(FDirectInput8) then
   begin
     // заносится код что уже создано
     FHRErrorCode := DIERR_ALREADYINITIALIZED;
     Exit;
   end;
 if (iHandle = 0) then Exit;
 inherited Create;
 // обнуление некоторых переменных
 FappWindowHandle          := iHandle;
 FDirectInput8             := nil;
 FDirectInputMouse         := nil;
 FDirectInputAcquire       := False;
 FDirectInputMouseAcquire  := False;
 // обнуление переменных мыши
 FMouseX       := 0;
 FMouseY       := 0;
 FMouseZ       := 0;
 FMouseDX      := 0;
 FMouseDY      := 0;
 FMouseDZ      := 0;
 FKMouseMove   := 1.0;
 FBoundsSet    := False;
 FBoundsLeft   := 0;
 FBoundsTop    := 0;
 FBoundsWidth  := 0;
 FBoundsHeight := 0;
 // все кнопки задаются отжатыми
 ResetMouseKey;
 ResetKeyboardKey;
 // устанавливаем связь с DirectInput
 FHRErrorCode := DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, FDirectInput8, nil);
 if Succeeded(FHRErrorCode) then
   FDirectInputAcquire := True
 else
   FDirectInput8 := nil;
end;

{==============================================================================
 повторное создание связи с объектом DirectInput
==============================================================================}

function TDIController.AcquireDirectInput: HResult;
begin
 // проверка не создан ли уже интерфейс
 if Assigned(FDirectInput8) then
   begin
     FHRErrorCode := DIERR_ALREADYINITIALIZED;
     Result := FHRErrorCode;
     Exit;
   end;
 // устанавливаем связь с DirectInput
 FHRErrorCode := DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, FDirectInput8, nil);
 if Succeeded(FHRErrorCode) then
   FDirectInputAcquire := True
 else
   FDirectInput8 := nil;
 Result := FHRErrorCode;
end;

{==============================================================================
 деструктор класса
==============================================================================}

destructor TDIController.Destroy;
begin
 UnAcquireMouse;
 UnAcquireKeyboard;
 // освобождаем интерфейс мыши
 FDirectInputMouseAcquire := False;
 if Assigned(FDirectInputMouse) then
   begin
     FDirectInputMouse._Release;
     FDirectInputMouse := nil;
   end;
 // освобождаем интерфейс клавиатуры
 FDirectInputKeybAcquire := False;
 if Assigned(FDirectInputKeyb) then
   begin
     FDirectInputKeyb._Release;
     FDirectInputKeyb := nil;
   end;
 // освобождаем интерфейс DirectInput
 FDirectInputAcquire := False;
 if Assigned(FDirectInput8) then
   begin
     FDirectInput8._Release;
     FDirectInput8 := nil;
   end;
 inherited;
end;

{==============================================================================
 захват мыши

 ===== входные величины =====
 startX:     начальная горизонтальная позиция
 startY:     начальная вертикальная позиция
 KMove:      коэффициент приращения позиции курсора

==============================================================================}

function TDIController.AcquireMouse(startX, startY, startZ: Integer; KMove: Single): HResult;
begin
 // проверяем не создан ли уже объект мыши
 if Assigned (FDirectInputMouse) then
   begin
     // объект уже существует
     FHRErrorCode := DIERR_ALREADYINITIALIZED;
     Result := FHRErrorCode;
     Exit;
   end;
 // установка начальных значений
 FDirectInputMouseAcquire := False;
 FMouseX := startX;
 FMouseY := startY;
 FMouseZ := startZ;
 FKMouseMove := KMove;
 // создать объект - мышь
 FHRErrorCode := FDirectInput8.CreateDevice(GUID_SysMouse, FDirectInputMouse, nil);
 if Failed(FHRErrorCode) then
   begin
     FDirectInputMouse := nil;
     Result := FHRErrorCode;
     Exit;
   end;
 // установить формат принимаемых данных, уровень кооперации и связать с устройством
 FHRErrorCode := FDirectInputMouse.SetDataFormat(c_dfDIMouse2);
 if Succeeded(FHRErrorCode) then
   FHRErrorCode := FDirectInputMouse.SetCooperativeLevel(FappWindowHandle, DISCL_NONEXCLUSIVE or DISCL_FOREGROUND);
 if Succeeded(FHRErrorCode) then
   FHRErrorCode := FDirectInputMouse.Acquire;
 if Failed(FHRErrorCode) then
   begin
     FDirectInputMouse._Release;
     FDirectInputMouse := nil;
   end
 else
   FDirectInputMouseAcquire := True;
 Result := FHRErrorCode;
end;

{==============================================================================
 освобождение мыши
==============================================================================}

function TDIController.UnAcquireMouse: HResult;
begin
 Result := S_OK;
 if FDirectInputMouseAcquire then
   begin
     if Assigned(FDirectInputMouse) then
       begin
         FHRErrorCode := FDirectInputMouse.Unacquire;
         Result := FHRErrorCode;
         FDirectInputMouse._Release;
         FDirectInputMouse := nil;
       end;
     FDirectInputMouseAcquire := False;
   end;
 // все кнопки мыши задаются отжатыми
 ResetMouseKey;
end;

{==============================================================================
 сброс сосотояния всех кнопок мыши
==============================================================================}

procedure TDIController.ResetMouseKey;
begin
 FDirectInputMouseKeyStat[0] := False;
 FDirectInputMouseKeyStat[1] := False;
 FDirectInputMouseKeyStat[2] := False;
 FDirectInputMouseKeyStat[3] := False;
 FDirectInputMouseKeyStat[4] := False;
 FDirectInputMouseKeyStat[5] := False;
 FDirectInputMouseKeyStat[6] := False;
 FDirectInputMouseKeyStat[7] := False;
end;


 
Sphinx ©   (2005-07-29 22:05) [6]

{==============================================================================
 установка прямоугольника, ограничивающего движение курсора мыши
==============================================================================}

procedure TDIController.SetMouseBound(aLeft, aTop, aWidth, aHeight: Integer);
begin
 FBoundsLeft   := aLeft;
 FBoundsTop    := aTop;
 FBoundsWidth  := aWidth;
 FBoundsHeight := aHeight;
 FBoundsSet    := True;
end;

{==============================================================================
 убрать ограничения на перемещение мыши
==============================================================================}

procedure TDIController.UnSetMouseBound;
begin
 FBoundsSet := False;
end;

{==============================================================================
 обновление данных мыши
==============================================================================}

procedure TDIController.UpdateMouseData;
var
 DirectInputMouseKey : TDIMouseState2;
begin
 // если связь и мышью не установлена
 if not(Assigned(FDirectInputMouse)) then
   begin
     // объект не создан
     FHRErrorCode := DIERR_NOTINITIALIZED;
     Exit;
   end;
 // подготовка переменной
 ZeroMemory(@DirectInputMouseKey, SizeOf (TDIMouseState2));
 // получить данные от мыши
 FHRErrorCode := FDirectInputMouse.GetDeviceState(SizeOf(TDIMouseState2), @DirectInputMouseKey);
 // проверка не потеряна ли связь с устройством
 if Failed(FHRErrorCode) then
   begin
     while ((FHRErrorCode = DIERR_INPUTLOST) or (FHRErrorCode = DIERR_NOTACQUIRED)) do
       FHRErrorCode := FDirectInputMouse.Acquire;
     Exit;
   end;
 if Failed(FHRErrorCode) then Exit;
 // проверяем состояние клавишь мыши
 FDirectInputMouseKeyStat[0] := KeyIsDown(DirectInputMouseKey.rgbButtons[0]);
 FDirectInputMouseKeyStat[1] := KeyIsDown(DirectInputMouseKey.rgbButtons[1]);
 FDirectInputMouseKeyStat[2] := KeyIsDown(DirectInputMouseKey.rgbButtons[2]);
 FDirectInputMouseKeyStat[3] := KeyIsDown(DirectInputMouseKey.rgbButtons[3]);
 FDirectInputMouseKeyStat[4] := KeyIsDown(DirectInputMouseKey.rgbButtons[4]);
 FDirectInputMouseKeyStat[5] := KeyIsDown(DirectInputMouseKey.rgbButtons[5]);
 FDirectInputMouseKeyStat[6] := KeyIsDown(DirectInputMouseKey.rgbButtons[6]);
 FDirectInputMouseKeyStat[7] := KeyIsDown(DirectInputMouseKey.rgbButtons[7]);
 // записываем текущие смещения
 FMouseDX := DirectInputMouseKey.lX;
 FMouseDY := DirectInputMouseKey.lY;
 FMouseDZ := DirectInputMouseKey.lZ;
 // вычисляем координаты мыши
 FMouseX := FMouseX + round(DirectInputMouseKey.lX * FKMouseMove);
 FMouseY := FMouseY + round(DirectInputMouseKey.lY * FKMouseMove);
 FMouseZ := FMouseZ + round(DirectInputMouseKey.lZ); { нет умножения на коэф. !!! }
 // если движения мыши ограничены - проверить
 if FBoundsSet then
   begin
     if FMouseX < FBoundsLeft then
       FMouseX := FBoundsLeft;
     if FMouseX > (FBoundsLeft + FBoundsWidth) then
       FMouseX := (FBoundsLeft + FBoundsWidth);
     if FMouseY < FBoundsTop then
       FMouseY := FBoundsTop;
     if FMouseY > (FBoundsTop + FBoundsHeight) then
       FMouseY := (FBoundsTop + FBoundsHeight);
   end;
end;

{==============================================================================
==============================================================================}

procedure TDIController.SetMouseTo(iX, iY, iZ: Integer);
begin
 FMouseX := iX;
 FMouseY := iY;
 FMouseZ := iZ;
end;

{==============================================================================
 "захват" клавиатуры
==============================================================================}

function TDIController.AcquireKeyboard: HResult;
var
 DIPDW: TDIPropDWord;
begin
 // проверка не существует ли уже объект
 if Assigned(FDirectInputKeyb) then
   begin
     FHRErrorCode := DIERR_ALREADYINITIALIZED;
     Result := FHRErrorCode;
     Exit;
   end;
 // создаем интерфейс устройства
 FHRErrorCode := FDirectInput8.CreateDevice(GUID_SysKeyboard, FDirectInputKeyb, nil);
 // задаем формат данных
 if Succeeded(FHRErrorCode) then
   FHRErrorCode := FDirectInputKeyb.SetDataFormat(c_dfDIKeyboard);
 // устанавливаем уровень кооперации
 if Succeeded(FHRErrorCode) then
   FHRErrorCode := FDirectInputKeyb.SetCooperativeLevel(FappWindowHandle, DISCL_NONEXCLUSIVE or DISCL_FOREGROUND);
 // устанавливаем параметры буфера
 if Succeeded(FHRErrorCode) then
   begin
     ZeroMemory(@DIPDW, Sizeof(DIPDW));
     with DIPDW do
       begin
         diph.dwSize := Sizeof(TDIPropDWord);
         diph.dwHeaderSize := Sizeof(TDIPropHeader);
         diph.dwObj := 0;
         diph.dwHow := DIPH_DEVICE;
         dwData := DIKeyboardBuffer;
       end;
     FHRErrorCode := FDirectInputKeyb.SetProperty(DIPROP_BUFFERSIZE, DIPDW.diph);
   end;
 // устанавливаем связь с клавиатурой
 if Succeeded(FHRErrorCode) then
   FHRErrorCode := FDirectInputKeyb.Acquire;
 // если какая-то операция была провалена - обнуляем объект
 if Failed(FHRErrorCode) then
   begin
     FDirectInputKeyb._Release;
     FDirectInputKeyb := nil;
   end
 else
   FDirectInputKeybAcquire := True;
 Result := FHRErrorCode;
end;

{==============================================================================
 "освобождаем" клавиатуру
==============================================================================}

function TDIController.UnAcquireKeyboard: HResult;
begin
 Result := S_OK;
 if FDirectInputKeybAcquire then
   begin
     if Assigned(FDirectInputKeyb) then
       begin
         FHRErrorCode := FDirectInputKeyb.Unacquire;
         Result := FHRErrorCode;
         FDirectInputKeyb._Release;
         FDirectInputKeyb := nil;          
       end;
     FDirectInputKeybAcquire := False;
   end;
 ResetKeyboardKey;
end;

{==============================================================================
 сброс всех кнопок клавиатуры
==============================================================================}

function TDIController.ResetKeybKey: TKeyboardStat;
var
 i: Byte;
begin
 for i := 0 to 255 do
   Result[i] := False;
end;

{==============================================================================
 надстройка над функцией сброса состояния кнопок клавиатуры    
==============================================================================}

procedure TDIController.ResetKeyboardKey;
begin
 FDirectInputKeybKeyStat := ResetKeybKey;
end;


 
Sphinx ©   (2005-07-29 22:07) [7]

{==============================================================================
 обновление данный о состоянии кнопок клавиатуры
==============================================================================}

procedure TDIController.UpdateKeybData;
var
 DirectInputKeybKey: array[0..DIKeyboardBuffer - 1] of TDIDeviceObjectData;
 dwElements: Cardinal;
 i: Cardinal;
begin
 // проверка на существование объекта
 if not(Assigned(FDirectInputKeyb)) then
   begin
     FHRErrorCode := DIERR_NOTINITIALIZED;
     Exit;
   end;
 // подготовка данных
 ZeroMemory(@DirectInputKeybKey, Sizeof(DirectInputKeybKey));
 dwElements := DIKeyboardBuffer;
 // получить данные из буфера клавиатуры
 FHRErrorCode := FDirectInputKeyb.GetDeviceData(SizeOf(TDIDeviceObjectData), @DirectInputKeybKey, dwElements, 0);
 // проверка на наличае связи с устройством и её установление
 if Failed(FHRErrorCode) then
   begin
     while ((FHRErrorCode = DIERR_INPUTLOST) or (FHRErrorCode = DIERR_NOTACQUIRED)) do
       FHRErrorCode := FDirectInputMouse.Acquire;
     Exit;
   end;
 // если связь с устройством не восстановлена - выйти
 if Failed(FHRErrorCode) then Exit;
 // обновление статуса кнопок
 if dwElements <> 0 then
   for i := 0 to dwElements - 1 do
     FDirectInputKeybKeyStat[DirectInputKeybKey[i].dwOfs] := KeyIsDown(DirectInputKeybKey[i].dwData);
end;

{==============================================================================
 обновить данные класса
==============================================================================}

procedure TDIController.Update;
begin
 UpdateMouseData;  // обновить данные мышы
 UpdateKeybData;   // обновить данные клавиатуры
end;

{==============================================================================
 получить ланные о состоянии клавишь мыши
==============================================================================}

function TDIController.GetMouseKeys: TMouseKeyStat;
begin
 Result := FDirectInputMouseKeyStat;
end;

{==============================================================================
 получить данные о кнопках клавиатуры
==============================================================================}

function TDIController.GetKeybKeys: TKeyboardStat;
begin
 Result := FDirectInputKeybKeyStat;
end;

end.


in uGameTypes.pas
 // структуры данных для контроллера DirectInput
 TMouseKeyStat = array[0..7] of Boolean;         // массив состояний клавишь мыши
 TKeyboardStat = array[0..255] of Boolean;       // массив состояний кнопок клавиатуры


in uGameConst.pas
 DIKeyboardBuffer = 16;                              // размер буфера клавиатуры


 
Sphinx ©   (2005-07-29 22:08) [8]

Лишнее - уберите, но принцип тут показан
клавиатура читется буферизованно,
мышь - непосредственно.


 
ink   (2005-07-30 15:38) [9]

Спасибо ребята!



Страницы: 1 вся ветка

Текущий архив: 2006.01.01;
Скачать: CL | DM;

Наверх




Память: 0.54 MB
Время: 0.042 c
2-1134643034
bav9
2005-12-15 13:37
2006.01.01
Виснет приложение при выводе окна Создание сообщения эл.почты


14-1133176085
syte_ser78
2005-11-28 14:08
2006.01.01
вопрос по хостингу


14-1134128959
Dok_3D
2005-12-09 14:49
2006.01.01
Роберт Блох


9-1122506838
Алгоритм
2005-07-28 03:27
2006.01.01
Самосборка паззлов Возможна ли ?


1-1133526751
Ugrael
2005-12-02 15:32
2006.01.01
как задать нужный переход по ENTER ?