如何:确定 ImageButton Web 服务器控件中的坐标

更新:2007 年 11 月

当用户单击 ImageButton 控件时,将向控件的 Click 事件的事件处理程序传递包含指示用户单击位置的坐标的参数。这允许您基于用户单击的位置执行不同的任务。

cftdhkwf.alert_note(zh-cn,VS.90).gif说明:

要将图像的特定区域定义为用户可单击的区域时,也可以使用 ImageMap 控件。

坐标信息作为 ImageButton 控件的 Click 事件的事件参数对象的组成部分发送。

确定用户单击位置的坐标

  1. ImageButton 控件的 Click 事件创建一个事件处理程序。在该方法中,事件参数对象的类型必须是 ImageClickEventArgs

  2. Click 事件处理程序中,获取 ImageClickEventArgs 参数对象的 XY 属性。

    x 坐标和 y 坐标用像素表示,图像左上角的坐标是 (0,0)。

    下面的示例显示如何确定用户在一个大小为 100 x 100 像素的图形上单击的位置。代码获取用户单击位置的 x 坐标和 y 坐标。然后,将它们与预设值进行比较,确定用户是否是在特定象限中单击的。结果显示在 Label 控件中。

    Protected Sub ImageButton1_Click(ByVal sender As System.Object, _
          ByVal e As System.Web.UI.ImageClickEventArgs) _
          Handles ImageButton1.Click
       Dim msg as String = ""
       Dim x As Integer = e.X
       Dim y As Integer = e.Y
    
       ' The button graphic is assumed to be 100x100 pixels.
       ' This checks coordinates against predetermined values that
       ' make up quadrants of the picture.
       If x >= 50 And y >= 50 Then
          msg = "Southeast"
       ElseIf x >= 50 And y < 50 Then
          msg = "Northeast"
       ElseIf x < 50 And y >= 50 Then
          msg = "Southwest"
       ElseIf x < 50 And y < 50 Then
          msg = "Northwest"
       End If
       Label1.Text = msg
    End Sub
    
    protected void ImageButton1_Click(object sender, 
        System.Web.UI.ImageClickEventArgs e)
    {
        string msg = "";   
        int x = e.X;   
        int y = e.Y;   
    
        // The button graphic is assumed to be 100x100 pixels.
        // This checks coordinates against predetermined values that
        // make up quadrants of the picture.
        if(x >= 50 && y >= 50)
        {
            msg = "Southeast";
        }
        else if(x >=50 && y < 50)
        {
             msg = "Northeast";
        }
        else if(x < 50 && y >= 50)
        {
            msg = "Southwest";
        }
        else if(x < 50 && y < 50)
        {
            msg = "Northwest";
        }
        Label1.Text = msg;
    }
    

请参见

参考

Button Web 服务器控件概述