Search code examples
c#winformsc++-climouseclick-eventcode-translation

How to check which mouse button was clicked during an MouseClick event in c++/cli?


It's supposed to work like this in c#, but what's the equivalent in c++/cli?

private void CustomControl_MouseClick(object sender, MouseEventArgs e) 
{        
   if (e.Button == MouseButtons.Right) 
   { 
     ... do something
   } 
} 

MouseButtons.Right, MouseButtons::Right and MouseButtons->Right all don't seem to compile. It always says

error C2039: 'Right' : is not a member of 'System::Enum'

Here is my c++/cli code:

System::Void WindowTest::pictureBoxTest_MouseClick(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e)
    {
        if (e->Button == MouseButtons::Left)
        {
        // do something
            }
}

Solution

  • From here you seem to be missing the :: before your MouseButtons::Right

      void panel1_MouseDown( Object^ /*sender*/, System::Windows::Forms::MouseEventArgs^ e )
      {
         // Update the mouse path with the mouse information
         Point mouseDownLocation = Point(e->X,e->Y);
         String^ eventString = nullptr;
         switch ( e->Button )
         {
            case ::MouseButtons::Left:
               eventString = "L";
               break;
    
            case ::MouseButtons::Right:
               eventString = "R";
               break;
    
            case ::MouseButtons::Middle:
               eventString = "M";
               break;
    
            case ::MouseButtons::XButton1:
               eventString = "X1";
               break;
    
            case ::MouseButtons::XButton2:
               eventString = "X2";
               break;
    
            case ::MouseButtons::None:
            default:
               break;
         }
         if ( eventString != nullptr )
         {
            mousePath->AddString( eventString, FontFamily::GenericSerif, (int)FontStyle::Bold, (float)fontSize, mouseDownLocation, StringFormat::GenericDefault );
         }
         else
         {
            mousePath->AddLine( mouseDownLocation, mouseDownLocation );
         }
    
         panel1->Focus();
         panel1->Invalidate();
      }