【问题标题】:Get the clicked drawn item获取点击的绘制项
【发布时间】:2016-04-03 03:21:28
【问题描述】:

我正在创建一个自定义项目列表,我在其中绘制所有项目。绘制项目很容易,找出点击了哪个项目是困难的部分,过去 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;
            }
        }
    }
}

【问题讨论】:

  • 看看at this answer - 它是为线条而写的;对于矩形,事物是使用 Contains 方法的事件简单。但是遍历 List 的基本思想是一样的
  • 要使用它,我必须为每个项目添加一个 Point 属性,我不能这样做。
  • 并非如此。不要使用 Line 类;只需写一些适用于您的项目的东西。使用矩形应该更简单..!

标签: c# winforms


【解决方案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;
        }
    }

当您找到一个匹配项时,或者即使您可能找到多个匹配项时,您可以决定该怎么做..

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    • 2020-10-09
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多