asp.net.ph

Skip Navigation Links

Determining Coordinates In an ImageButton

Controls You Can Use on Web Forms   ASP.NET Standard Controls   Button Controls


You can use an ImageButton as an image map — that is, you can capture the precise x and y coordinates where a user clicked within the image. This allows you to perform different tasks based on where the user clicked.

Coordinate information is sent as part of the event argument object for the ImageButton control’s Click event.

To determine the coordinates where a user clicks

  1. Define a method to handle the ImageButton control’s Click event. The event argument object for the method must be of type ImageClickEventArgs.
  2. In the method, determine the X and Y properties of the event argument object.

protected void getClickCoords ( object src, ImageClickEventArgs e ) {
   int x=e.X;
   int y=e.Y;
   ...
}
  C# VB

The x and y coordinates are expressed in pixels offset from the upper left corner of the image ( 0,0 ).

  1. Check the coordinates against predetermined values in the image to see if the user clicked on a particular quadrant, then do something exciting. In this example, the results are simply displayed in a set of Label s.
       if ( x>20 && x<35 && y>72 && y<88 ) {
          message.Text = "That was Bill’s ear you clicked.";
       }
       else if ( x>42 && x<58 && y>48 && y<64 ) {
          message.Text = "That was Bill’s eye you nicked.";
       }
       else if ( y<72 && y>60 ) {
          message.Text = "That was Bill’s nose you picked.";
       }
       else if ( y<92 && y>74 ) {
          imgButt.ImageUrl="tongue.gif";
          message.Text = "bwaaahaaahaa!";
       }
       else {
          whoops ( );
       }
       ...
       // optionally display coordinates
       Label1.Text = "X:" + x.ToString ( );
       Label2.Text = "Y:" + y.ToString ( );
       ...

The following sample illustrates using the ImageButton control as an image map.

ImageButton2.aspx
Run Sample | View Source
See Also

Creating Graphical Button Controls   ImageButton Web Control



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note