# How to let graphics primitives respond to a mouse click?

**URL:** <https://root-forum.cern.ch/t/how-to-let-graphics-primitives-respond-to-a-mouse-click/28250>\
**Category:** Howto\
**Tags:** graphics\
**Created:** [March 9, 2018, 11:53am UTC](https://root-forum.cern.ch/t/how-to-let-graphics-primitives-respond-to-a-mouse-click/28250 "2018-03-09T11:53:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![couet](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/couet/32/12037_2.png) [@couet](https://root-forum.cern.ch/u/couet)\
**Post date:** [March 9, 2018, 11:53am UTC](https://root-forum.cern.ch/t/how-to-let-graphics-primitives-respond-to-a-mouse-click/28250/1 "2018-03-09T11:53:56Z")

</div>

This can be done by adding a `TExec` object in a `TCanvas`. The following macro gives an example. It generates 50 small triangles randomly in the canvas. Each triangle get a unique identifier and a random color. Once this macro have been executed, clicking on any triangle shows a message giving the triangle identifier and its color.

```auto
void triangles(Int_t ntriangles=50) {
  auto c1 = new TCanvas("c1","triangles",10,10,700,700);
  TRandom r;
  auto dx = 0.2;
  auto dy = 0.2;
  auto ncolors = gStyle->GetNumberOfColors();
  Double_t x[4],y[4];
  for (Int_t i=0;i<ntriangles;i++) {
     x[0] = r.Uniform(.05,.95); y[0] = r.Uniform(.05,.95);
     x[1] = x[0] + dx*r.Rndm(); y[1] = y[0] + dy*r.Rndm();
     x[2] = x[1] - dx*r.Rndm(); y[2] = y[1] - dy*r.Rndm();
     x[3] = x[0]; y[3] = y[0];
     auto pl = new TPolyLine(4,x,y);
     pl->SetUniqueID(i);
     pl->SetFillColor(ncolors*r.Rndm());
     pl->Draw("f");
  }
  c1->AddExec("ex","TriangleClicked()");
}

void TriangleClicked() {
   //this action function is called whenever you move the mouse
   //it just prints the id of the picked triangle
   //you can add graphics actions instead
   auto event = gPad->GetEvent();
   if (event != 11) return; //may be comment this line
   auto select = gPad->GetSelected();
   if (!select) return;
   if (select->InheritsFrom("TPolyLine")) {
      auto pl = (TPolyLine*)select;
      printf("You have clicked triangle %d, color=%d\n",
              pl->GetUniqueID(),pl->GetFillColor());
   }
}

```
