徒然なるままにコーディング

ジョイスティックとMIDIメッセージの巻。
キーコンフィグが要るなあ。

#include <stdio.h>
#include <windows.h>
#include <mmsystem.h>
#pragma comment(lib,"winmm.lib")

int getValidJoystick()
{
  const int JOYNUM = joyGetNumDevs();
  JOYINFOEX info;
  info.dwSize = sizeof(JOYINFOEX);
  info.dwFlags = JOY_RETURNALL;
  int i = 0;
  do
  {
    int result = joyGetPosEx(i,&info);
    if(result == JOYERR_PARMS) break;
    if(result == JOYERR_NOERROR) return i;
    ++i;
  }while(i<JOYNUM);
  return -1;
}

//int WINAPI WinMain(HINSTANCE,HINSTANCE,char*,int)
int main()
{
  int joyID = getValidJoystick();
  if(joyID<0){
    return 0;
  }
  printf("joyID:%d\n",joyID);
  JOYINFOEX info={0};
  info.dwSize = sizeof(JOYINFOEX);
  info.dwFlags = JOY_RETURNALL;
  
  HMIDIOUT hMidiOut;
  midiOutOpen(&hMidiOut,(UINT) MIDI_MAPPER, NULL, 0L, 0L);

  int scale[9] = { 60, 62, 64, 65, 67, 69, 71, 72, 74};
  int flags[9] = { 0};

  while(!(info.dwButtons & 0x800)){
    joyGetPosEx(joyID, &info);
    /* printf("%x %x %x %x %x %x %x\n",
	   info.dwXpos, info.dwYpos,
	   info.dwZpos, info.dwRpos,
	   info.dwUpos, info.dwVpos,
	   info.dwButtons); */
    for(int i=9,m=0x200; m; --i,m>>=1)
    {
      if(info.dwButtons & m){
	if(flags[i] == 0){
	  int msg = 0x90 | (scale[i] << 8) | (0x64 << 16);
	  midiOutShortMsg(hMidiOut, msg); // Note On
	  flags[i] = 1;
	}
      }else{
	if(flags[i] == 1){
	  int msg = 0x90 | (scale[i] << 8) | (0x00 << 16);
	  midiOutShortMsg(hMidiOut, msg); // Note Off
	  flags[i] = 0;
	}
      }
    }
  }
  midiOutClose(hMidiOut);
  return 0;
}