检查是否在特定区域中单击了鼠标

时间:2009-08-26 20:23:44

标签: vb.net winforms

如何检查是否在表单“?

上的特定坐标平面中单击鼠标

2 个答案:

答案 0 :(得分:1)

使用MouseEventArgs.X和MouseEventArgs.Y查看它们是否在坐标平面内。

这个答案只需点击一下,就可以在我上一期问题的回答中找到的链接。

http://msdn.microsoft.com/en-us/library/system.windows.forms.mouseeventargs_members.aspx

<强>

方案: 我有一个矩形的区域,我想处理点击。

形状的左上角位于28,83(左,上)

尺寸为225,52(宽度,高度)

因此,如果位置X(左侧介于28和28 + 225(253)之间且位置Y介于83和83 + 52(135)之间,则位于边界内。

代码示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.MouseClick += new MouseEventHandler(Form1_MouseClick);
        }

        void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.X >= 28 && e.X <= 253 && e.Y >= 83 && e.Y <= 135)
            {
                MessageBox.Show("Clicked within the rectangle");
            }
            else
            {
                MessageBox.Show("Clicked outside the rectangle");
            }
        }
    }
}

答案 1 :(得分:1)

用于标记从coord 100,100开始的100像素方形区域的VB代码。 (设置您自己的值。)

   Private Sub frm_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick

      Dim x As Integer = e.Location.X
      Dim y As Integer = e.Location.Y

      If x > 100 AndAlso x < 200 AndAlso y > 100 AndAlso y < 200 Then
         MessageBox.Show("Inside")
      Else
         MessageBox.Show("Outside")
      End If

   End Sub

当然,这只会在鼠标点击表单表面时捕获鼠标。如果单击表单上的某个控件,则必须仔细考虑要执行的操作。