获取单击的绘制项目

时间:2016-04-02 18:52:52

标签: c# winforms

我正在创建一个自定义项目列表,我在其中绘制所有项目。绘制项目很容易,找出点击的项目是困难的部分,我一直试图弄清楚过去2小时。有谁知道如何找出点击了哪个项目? 这是我的代码

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

namespace WindowsFormsApplication2
{
    class MyList : Control
    {
        #region Constructor
        public MyList()
        {
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
        }
        #endregion

        #region Properties
        private string[] Items = new string[] { "Item 1", "Item 2", "Item 3", "Item 4" };

        private int _ItemHeight = 25;
        public int ItemHeight
        {
            get { return _ItemHeight; }
            set { _ItemHeight = value; this.Invalidate(); }
        }
        #endregion

        #region Mouse Events
        protected override void OnClick(EventArgs e)
        {
            // Get the clicked item
        }
        #endregion

        protected override void OnPaint(PaintEventArgs e)
        {
            int ItemYPosition = 0;
            foreach (string Item in Items)
            {
                Rectangle ItemRectangle = new Rectangle(0, ItemYPosition, this.Width, _ItemHeight);
                e.Graphics.DrawRectangle(Pens.Red, ItemRectangle);
                ItemYPosition += _ItemHeight;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Rectangle有几个很好的方法。一个是Contains(Point)

    protected override void OnClick(EventArgs e)
    {
        // Get the clicked item
        int ItemYPosition = 0;
        foreach (string Item in Items)
        {
            Rectangle ItemRectangle = new Rectangle(0, ItemYPosition,
                                                    this.Width, _ItemHeight);

            if (ItemRectangle.Contains(e.Location)) // found one hit!

            ItemYPosition += _ItemHeight;
        }
    }

由您决定在发现命中时该做什么,或者即使您可能发现多次击中......