Handling Multiple Mice with Raw Input

Warning! Some information on this page is older than 3 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

23:29
Thu
21
Mar 2013

Handling Multiple Mice with Raw Input

When you connect second USB mouse to your computer, you don't have second cursor to move on the screen and click on things. Instead you can move and click the single cursor with both mice. What if you want to distinguish messages from multiple mice in your program? I found the solution here. I downloaded and looked at the source code of MouseParty.zip linked from this page.

Handling multiple mice is possible using part of WinAPI called Raw Input. If you have <Windows.h> included, have your WinAPI window and message loop, you only need to initialize Raw Input like this:

RAWINPUTDEVICE device;
device.usUsagePage = 0x01;
device.usUsage = 0x02;
device.dwFlags = 0;
device.hwndTarget = 0;
RegisterRawInputDevices(&device, 1, sizeof device);

You then start to receive WM_INPUT message, which should be handled this way:

case WM_INPUT:
  OnRawInput(
    GET_RAWINPUT_CODE_WPARAM(wParam) == RIM_INPUT,
    (HRAWINPUT)lParam);
  // Must call DefWindowProc!
  break;

Where OnRawInput is my function:

std::vector<char> m_RawInputMessageData; // Buffer

void OnRawInput(bool inForeground, HRAWINPUT hRawInput)
{
    UINT dataSize;
    GetRawInputData(
      hRawInput, RID_INPUT, NULL, &dataSize, sizeof(RAWINPUTHEADER));

    if(dataSize == 0)
      return;
    if(dataSize > m_RawInputMessageData.size())
        m_RawInputMessageData.resize(dataSize);

    void* dataBuf = &m_RawInputMessageData[0];
    GetRawInputData(
      hRawInput, RID_INPUT, dataBuf, &dataSize, sizeof(RAWINPUTHEADER));

    const RAWINPUT *raw = (const RAWINPUT*)dataBuf;
    if (raw->header.dwType == RIM_TYPEMOUSE)
    {
        HANDLE deviceHandle = raw->header.hDevice;

        const RAWMOUSE& mouseData = raw->data.mouse;

        USHORT flags = mouseData.usButtonFlags;
        short wheelDelta = (short)mouseData.usButtonData;
        LONG x = mouseData.lLastX, y = mouseData.lLastY;

        wprintf(
            L"Mouse: Device=0x%08X, Flags=%04x, WheelDelta=%d, X=%d, Y=%d\n",
            deviceHandle, flags, wheelDelta, x, y);
    }
}
Mouse: Device=0x0001003D, Flags=0001, WheelDelta=0, X=0, Y=0
Mouse: Device=0x0001003D, Flags=0002, WheelDelta=0, X=0, Y=0
Mouse: Device=0x0001003D, Flags=0000, WheelDelta=0, X=-1, Y=0
Mouse: Device=0x0001003D, Flags=0004, WheelDelta=0, X=0, Y=0
Mouse: Device=0x0001003D, Flags=0008, WheelDelta=0, X=0, Y=0
Mouse: Device=0x0001003D, Flags=0400, WheelDelta=120, X=0, Y=0
Mouse: Device=0x0001003D, Flags=0400, WheelDelta=-120, X=0, Y=0
Mouse: Device=0x0001003D, Flags=0000, WheelDelta=0, X=1, Y=0
Mouse: Device=0x0001003D, Flags=0000, WheelDelta=0, X=1, Y=0
Mouse: Device=0x0001003D, Flags=0000, WheelDelta=0, X=2, Y=-1
Mouse: Device=0x0001003D, Flags=0000, WheelDelta=0, X=1, Y=-1

If you want to know in advance what mice are available in the system, you can enumerate them with following code:

UINT numDevices;
GetRawInputDeviceList(
  NULL, &numDevices, sizeof(RAWINPUTDEVICELIST));
if(numDevices == 0) return;

std::vector<RAWINPUTDEVICELIST> deviceList(numDevices);
GetRawInputDeviceList(
  &deviceList[0], &numDevices, sizeof(RAWINPUTDEVICELIST));

std::vector<wchar_t> deviceNameData;
wstring deviceName;
for(UINT i = 0; i < numDevices; ++i)
{
  const RAWINPUTDEVICELIST& device = deviceList[i];
  if(device.dwType == RIM_TYPEMOUSE)
  {
    wprintf(L"Mouse: Handle=0x%08X\n", device.hDevice);

    UINT dataSize;
    GetRawInputDeviceInfo(
      device.hDevice, RIDI_DEVICENAME, nullptr, &dataSize);
    if(dataSize)
    {
      deviceNameData.resize(dataSize);
      UINT result = GetRawInputDeviceInfo(
        device.hDevice, RIDI_DEVICENAME, &deviceNameData[0], &dataSize);
      if(result != UINT_MAX)
      {
        deviceName.assign(deviceNameData.begin(), deviceNameData.end());
        wprintf(L"  Name=%s\n", deviceName.c_str());
      }
    }

    RID_DEVICE_INFO deviceInfo;
    deviceInfo.cbSize = sizeof deviceInfo;
    dataSize = sizeof deviceInfo;
    UINT result = GetRawInputDeviceInfo(
      device.hDevice, RIDI_DEVICEINFO, &deviceInfo, &dataSize);
    if(result != UINT_MAX)
    {
      assert(deviceInfo.dwType == RIM_TYPEMOUSE);
      wprintf(
        L"  Id=%u, Buttons=%u, SampleRate=%u, HorizontalWheel=%s\n",
        deviceInfo.mouse.dwId,
        deviceInfo.mouse.dwNumberOfButtons,
        deviceInfo.mouse.dwSampleRate,
        deviceInfo.mouse.fHasHorizontalWheel ? L"1" : L"0");
    }
  }
}

But the system on my PC reports 3 mouse devices even when I have only one USB mouse connected. Names are also quite cryptic. So it's not very useful I think.

Mouse: Handle=0x0001003F
  Name=\\?\Root#RDP_MOU#0000#{378de44c-56ef-11d1-bc8c-00a0c91405dd}
  Id=2, Buttons=2, SampleRate=60, HorizontalWheel=0
Mouse: Handle=0x0001003D
  Name=\\?\HID#VID_09DA&PID_000E#6&2ff89cff&0&0000#{378de44c-56ef-11d1-bc8c-00a0c91405dd}
  Id=256, Buttons=5, SampleRate=100, HorizontalWheel=0
Mouse: Handle=0x0001003B
  Name=\\?\HID#VID_062A&PID_0201&MI_01&Col01#7&136f4655&0&0000#{378de44c-56ef-11d1-bc8c-00a0c91405dd}
  Id=256, Buttons=0, SampleRate=0, HorizontalWheel=0

Comments (5) | Tags: winapi | Author: Adam Sawicki | Share

Comments

Kiran
2015-07-21 00:09:20
I have two questions:
My application requires two mice to be connected to the pc at the same time. I want only one of them to be configured to read the Raw Input Data on the console. The code you have posted reads the data from both the devices when moved. Do you think it's possible to disable one of the mouse from not reading Raw Input without altering the functions of that mouse that's being disabled?

Also the enumeration code when I place it inside the OnRawInput function, gives following error:

"assert" : identifier not found.
Have I forgotten to include any library

Fyi,i am using visual studio 2013
Kiran
2015-07-23 19:59:54
i just had to include the assert.h library. This eliminates the "assert" identifier not found
wxm
2016-03-29 09:54:29
http://asawicki.info/news_1319_game_programming_fffffuuuu.html?x=viewnews&id=1319
https://www.google.co.jp/search?q=Comments+site:http://asawicki.info/&biw=1309&bih=735&noj=1&ei=DDH6Vq3sJs-UjwOuoab4DA&start=130&sa=N
http://asawicki.info/news_1328_rendering_mandelbrot_and_julia_fractal.html?x=viewnews&id=1328
http://asawicki.info/news_871_wskazniki_na_metody_w_c.html?x=viewnews&id=871
http://asawicki.info/news_944_w_czym_pisac_skrypty.html?x=viewnews&id=944
http://asawicki.info/news_1063_piosenki_o_grach.html?x=viewnews&id=1063
http://asawicki.info/news_1486_how_to_make_visual_studio_debugger_not_step_into_stl.html?x=viewnews&id=1486
http://asawicki.info/news_1242_dobry_hex_edytor.html?x=viewnews&id=1242
http://asawicki.info/news_1511_cppdepend.html?x=viewnews&id=1511
http://asawicki.info/news_1211_total_commander_a_foldery_specjalne.html?x=viewnews&id=1211
http://asawicki.info/news_1604_adventures_with_porting_code_to_visual_studio_2015_and_no_directx_sdk.html?x=viewnews&id=1604
http://asawicki.info/news_1161_praca_magisterska_o_silniku_3d.html?x=viewnews&id=1161
http://asawicki.info/news_1232_skad_brac_ikonki.html?x=viewnews&id=1232
http://asawicki.info/news_1270_zabawy_z_gimp-em_1_-_bloom.html?x=viewnews&id=1270
http://asawicki.info/news_1273_czcionki_z_komputera_atari.html?x=viewnews&id=1273
http://asawicki.info/news_1202_autoit_-_automatyzacja_windows.html?x=viewnews&id=1202
wxm
2016-03-29 09:59:55
beautiful www.nike-air-max.ca things www.bottega-veneta.us.com to www.michael-kors-outlet-online.us.org read www.swarovskijewelry.com.co more, www.oakley.org.es look www.michael-kors-outlet.us.org for www.michaelkors-uk.org.uk a www.oakley-sunglasses-canada.ca long www.oakleysunglasses-cheap.in.net time, www.ugg-boots-australia.com.au I www.ugg-boots.ca felt www.michael-kors-australia.com.au closer www.chanelhandbags.net.in to www.coco-chanel.com.de reality www.ralph-laurenoutlet.ca very www.asicsgels.de far away, www.toms-shoes.net.co life www.burberryoutlet-canada.ca is www.michael-korshandbags.org.uk short, www.weddingdressesuk.org.uk if www.rayban-sunglasses.us.org put www.louis--vuitton.org.uk too www.rayban.com.de much www.nikefree5.net time www.michael-kors.com.co is www.nikefactory.org spent www.new-balance.ca on www.converse.com.de practical www.burberry-outlet.net.co things, www.bebeclothing.in.net really www.kate-spade.in.net is www.oakley-sunglasses.mex.com a waste of www.jimmy-chooshoes.com life, www.nike-air-max.com.se but www.nike-free-run.de some www.louisvuitton-outlets.us things, www.tommy-hilfiger-online-shop.de but www.michaelkorsoutlet-online.ar.com if www.true-religion.com.co the raw www.the-northfacejackets.us.com flavor, leisure www.airjordans.us goods airmax.shoesoutlet.us.com for gossip, www.replicarolex-watches.us.com so www.burberry-handbags2016.in.net I www.hermesbirkin-bag.net love www.michael--kors.us.com romantic www.longchamp-bags.us.com dreamer, www.yoga-pants.ca but www.mcmhandbags.com.co I www.oakley--sunglasses.com.au love airmax.misblackfriday.com real www.ralphlaurenoutlet-online.us.com life.Day www.outlet-burberry.net.co in www.pandora-charms-canada.ca a www.ralphlaurenoutletonline.us.org hurry, www.ralphlaurenpolos.in.net took www.coach-factoryyoutletonline.net all www.ray--ban.ca the www.designer-handbagsoutlet.us.com joy www.ugg-australia.com.de and www.guccishoes.com.co sadness, a lot www.tiffany-jewelry.net of www.retro-jordans.com things, www.marcjacobs.us.com not www.coachblackfriday.com enough time www.jimmy-choos.com to www.nikeair--max.fr recall, Chaoyang uggaustralia.misblackfriday.com July, www.ralph-lauren.com.au early www.pandora.com.de June www.soft-ballbats.com already www.abercrombie-fitchsale.com covered www.adidas-superstar.de confused. Season www.guccishoes-uk.co.uk removed, www.michael-kors-handbags.us.com landscape www.burberrybags-outlet.com transformation, the www.tiffany-andco.us.com so-called www.adidas.com.se forever www.pandora-charms.org.uk always far-fetched, www.guccishoes.in.net time, www.tomsoutlet-online.com not www.soccer-shoes.us.com to www.pulseras-pandora.com.es be www.mizuno-running.net squandered, www.the-north-face.ca the www.rolexwatchesforsale.us.com true www.nikeskos.dk meaning www.ray-ban-outlet.us.com of www.ralphs-lauren.co.uk life is to www.louisvuitton.so enjoy www.uggsoutlet.com.co the www.adidas.org.es good www.coach-factoryoutlet.net.co in the www.handbagsoutlet.net.co flat, www.ralphlaurenoutletonline.in.net I www.timberlandshoes.net.co Dimei www.cheapuggboots.us.com fireworks, www.burberry-handbagsoutlet.com.co also www.instylers.us.com read www.salomon-schuhe.com.de the www.coachoutletstore.net.co leisure, www.prada-shoes.com.co with a www.katespadeoutlet.gb.net touch www.nike-roshe-run.de of www.tiffanyand-co.net.co ink, www.ray-bansunglasses.net painting www.nike-schoenen.co.nl a www.harrods-london.co.uk thin www.oakley-outletstore.in.net clear www.abercrombie-fitchs.us.com Huan, www.coach-factory.in.net look www.cheap-oakleyglasses.us.com lush www.nikestore.us green, www.jordanretro.org covered www.timberlands-paschere.fr with www.mkoutletonline.us.com mottled www.polo-ralph-lauren.de wall. www.coachoutletstore-online.com.co This July, www.juicycoutureoutlet.net.co I www.uggboots.net.co kept www.ralphlauren-polos.co.uk the www.nikemercurial.in.net book's www.oakley.com.de swoosh; www.timberlandbootsoutlet.us.com this www.uggs-onsale.net July, www.hermesbags.jp.net I www.christian-louboutin-shoes.ca dream in www.oakleysunglass-outlet.net Lijiang; www.christianlouboutinshoes.jp.net this www.nike-air-max.us July, www.bcbg-dresses.com and has www.newbalance.com.es been www.thenorthface.com.de well, www.maccosmetics.gr.com not www.zxcoachoutlet.com made www.lululemonoutlet.gb.net sad.If you www.longchamp.com.de can www.ralphslauren-outlet.co.uk do www.reebok.com.de if www.adidas-superstar.nl a www.uggs.co.nl light www.oakleys-sunglasses.us.com breeze right www.eyeglassframes.in.net woman, placed in www.abercrombie-and-fitch.us.com the www.giuseppezanotti.com.co text www.michael-kors.com.es soul, www.nikestore.com.de written www.supra-shoes.org imprint www.michaelkors.so of www.gucci-shoes.net life, www.eyeglassesonline.us.com write www.nike-maxfr.com thin www.omegarelojes.es cool www.abercrombieand-fitch.ca and www.ghdhair-straighteners.co.uk clear www.oakleyoutlet.ar.com Huan, www.ralphlauren-polos.com.co occasionally www.longchamp.com.co write supra.shoesoutlet.us.com love, www.chanel-bags.com.co but www.polo-outlets.com.co never give www.raybans-sunglassesoutlet.in.net love, keep www.tommy-hilfiger-canada.ca a www.nike-rosherun.nl clear www.adidas-schuhe-online.de gel www.coachhandbags2016.us.com Bay, www.ralphlaurenoutlet.us.com look www.montblanc--pens.in.net for www.cheapoakley-sunglasses.com a www.canada-goosesjackets.us.com parts www.nike--freerun.co.uk of the peace, www.rolex-watches.us.com the joy www.michaelkorsoutletonline-sale.us.com and www.mcm-bags.in.net sorrow www.rayban-sunglassesoutlet.co.uk of all www.oakleys-glasses.us.com his www.toms-shoes.com.co writings, www.louis-vuittonoutletcanada.ca and www.polooutlets-store.com text www.hollister-clothing.in.net only www.hogan.com.de affair www.louboutin.jp.net has www.juicycouture.com.co nothing www.cheapmichaelkors.us.org to do www.coco-chanels.us.com with www.nikeair-max.es the www.ugg-bootsclearance.com other.Morning www.nike.org.es time, www.celine-bags.org with www.tnf-jackets.us.com a www.giuseppe-zanotti.net tranquil www.uggsaustralia.com.co and www.rayban-wayfarer.in.net contented www.coach-purseoutlet.net Zen www.hollister.us.org cloud water, www.poloralphlaurenoutlet.net.co eyes www.nikerosherun.us closed, www.prada.com.de the www.tommy-hilfiger.co.nl heart www.burberry-outletonlinesale.in.net distant www.lauren-ralph.co.uk exile, Wind www.cheap-michaelkors.com and www.uggs.in.net Smoke www.nikefree-run.net curl www.cheap-jordans.net in the www.ralphlaurenepolo.com mountains, www.nike-huarache.nl such www.cheap-nike-shoes.net as www.truereligionjeans.net.co Dai, www.guccihandbags.net.co ups www.fashionclothes.us.com and www.adidas--canada.ca downs, www.christian--louboutin.in.net indeed, www.truereligion-outlet.com.co like www.burberry2016.co.uk a www.ugg-boots.us.org thread, www.montres-pascher.fr the www.ray-banocchiali.it ups and www.raybans.us.org downs www.tomsoutletonline.net of www.uggboots.com.de life, www.guccioutlet-sale.in.net with www.truereligion-outlet.us.org long www.lululemon-australia.com.au Qingyuan . www.longchampoutlet.com.co Flowers followed www.babyliss-pro.us.com the www.kate-spade.gb.net road, facing www.polos-ralphlauren.us.com the www.hollisters-canada.ca sun www.tommy-hilfigeroutlet.com slowly www.salvatoreferragamo.in.net forward, then the www.christianlouboutinoutlet.net.co mind www.chi-flatiron.us.com is calm, www.air-huarache.co.uk quiet www.thejoreseproject.com as www.nikefree-run.org.uk the www.rayban.org.es lake, the www.hermes-outlet.com.co water www.asics-outlet.us.com peach, www.abercrombie-hollister.nl flower www.swarovski--uk.me.uk with www.louisvuitton.jp.net water, www.uhren-shop.com.de just www.ghd-hairstraightener.net like www.burberryonlineshop.de the www.iphone-cases.net.co fate www.converse.net.co of www.toryburchsale.com.co this www.cheap-baseballbats.net world, www.jordan-shoes.com.co do www.bcbg-max-azria.ca not www.rolexwatches-canada.ca ask www.christianlouboutinshoesoutlet.org why, www.the-northface.net.co regardless airhuarache.shoesoutlet.us.com of www.chiflatiron.net.co come www.nike-skor.com.se and www.burberrys-outlet.co.uk go, www.tommyhilfigeroutlet.in.net only flowers www.converse-shoesoutlet.com need www.beatsbydre.com.co to www.michael-kors-canada-outlet.ca remember www.hollister-abercrombie.com.se Lu www.levisjeans.com.co Qing, www.thenorth-faces.co.uk Yue www.tiffanyandco-canada.ca possessor of www.swarovski-australia.com.au the www.marc-jacobs.us.com green www.ugg-uggboots.net heart, cool www.air-max.com.de count. www.coachoutlet-online.com.co Sunlight www.thomas-sabo.com.de penetration mist, www.beats-by-dre.com.co alluding www.oakleyoutlet-online.us.com on www.burberryoutlet2016.us.com the www.tocoachoutlet.com lake, www.new-balance-schuhe.de the www.cheapoakley-sunglasses.in.net water www.michaelkorsbags.us.org green, www.pradahandbags.net.co clear, www.mmoncler-outlet.com sparkling, www.toms-shoesoutlet.net on www.omega-watches.us.com the www.replica-watches.com.co beach, www.tiffany-andco.com.au there www.newbalance-outlet.org are www.insanity-workout.us.com birds www.p90xworkout.us.com flying www.abercrombie-kids.us.com over www.gucci-taschen-outlet.de from www.adidasshoes.top time www.soccer-shoesoutlet.com to www.moncler-outlet.us.org time, www.pumashoes.in.net the www.rolex-watch.me.uk sky www.swarovski-online-shop.de blue www.converse-shoes.net and www.michaelkors.co.nl empty, www.lululemoncanada.ca with a quiet www.burberryoutlet-sale.in.net life www.swarovskicanada.ca after www.nfl-jersey.us.com ups www.nike-shoes-canada.ca and www.ralphlaurenonlineshop.de downs, this time www.nike-shoesoutlet.us.com the www.vans-shoes.net heart www.toryburchoutlet-sale.us.com is www.louisvuittons.com.co close www.mcm-handbags.org to www.pumaonline-shop.de nature, www.toryburch-sandals.in.net without www.pandorajewelry.top the www.louis-vuitton-taschen.com.de slightest www.thomas-sabos.org.uk ripples, www.michael-kors.net.co content with this www.nike-schuhe.com.de quiet www.burberry-outletstore.net and www.northfaceoutlet.com.co peaceful. www.toms-outlets.us.com An www.vans-schuhe.com.de end, www.newoutletonlinemall.com wins www.edhardy.us.org the www.cheapjerseys.com.co snow www.mk-outlet.us.com lotus, www.rosheruns.us world www.mcmsworldwide.com clarity, www.ralph-laurens.org.uk years www.nike-tnrequinpascher.fr of www.louisvuitton-outlet.com.co silence, www.tory-burchshoesoutlet.net the www.hollisteronlineshop.com.de heart www.michaelkorsoutlet.ar.com is www.vans-shoes.co.uk also www.airmax-2015.org safe.Time, www.scarpe-hoganoutlets.it very www.rosherun.org.uk long. I www.airmax-90.org know, www.beats-headphone.com.co I www.replica-handbags.net.co can stay www.longchamps.us.com in www.ferragamo.com.co my www.bottegaveneta-bagsoutlet.com mind there www.hollisterclothingstore.org are www.michael-kors-taschen.com.de limitations, not www.nike-air-max.com.au the www.barbour-factory.com majority, www.toms--outlet.com.co can only www.rayban.co.nl rely on www.christian-louboutinshoes.com.co these www.louis-vuittonblackfriday.com words to memory.Time, www.cheap-raybans.com is very www.yoga-pants.net.co short. www.nike-air-force.de I www.cheapjerseys.us.org understand, www.michaelkors-outlet-online.com.co you www.longchamp-handbagsoutlet.us.com can www.woolrich-clearance.com never www.tomsshoes-outlet.us.com forget so www.cheapshoes.com.co little, www.longchamphandbagsoutlet.net so www.pandorajewellery.com.au I nike.shoesoutlet.us.com was www.mcmbags.net in www.designerhandbagsoutlet.net.co such www.pradaoutlet.com.co a www.tiffany-und-co.de manner www.nike-roshe-run.com.es so as www.thenorthfacejackets.net.co to www.horloges-rolex.nl leave www.louis-vuitton-australia.com.au some www.tommy-hilfiger.com.de more.Youth, www.basketballshoes.com.co is very www.christianlouboutin.org.uk long. www.the-northface.com.co In www.gucci-outletstore.com life, www.jordanrelease-dates.us.com shiny www.ferragamoshoes.in.net people, www.michaelkors.com.se in www.beatsbydrdre.co.com fact, www.burberrys-outlet2016.com that www.calvin-kleins.us.com a figure, www.nikeshoesoutlet.org.uk how the passage www.valentino-shoesoutlet.us.com of www.airhuarache.co.uk time, www.michaeljordan.com.de or www.swarovski-crystal.us.com the www.nike-airmaxinc.co.uk whole www.canadagooses-2016.com dazzling www.coach-outletonline.net.co Love.Youth, www.tommyhilfiger.net.co is www.prada-handbags.com.co very www.nike-air-max.com.de short. www.cheaprayban.com.co In www.newbalance-shoes.org life, www.wedding--dresses.ca flickering www.barbour-jacketsoutlet.com days www.maccosmetics.net.co
Hannes
2016-07-07 22:56:17
I wrote a blog article on how to implement two mice. It was inspired by the posts above. Here it is:

https://hannespfeiffer.net/2016/07/07/how-to-use-multiple-mice-with-glfw/

Post comment

Nick *
Your name or nickname
E-mail
Your contact information (optional, will not be shown)
Text *
Content of your comment
Calculate *
(* - required field)
STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2016 Adam Sawicki
Copyright © 2004-2016 Adam Sawicki