【问题标题】:How to detect a click of a dynamically drawn graphic?如何检测动态绘制图形的点击?
【发布时间】:2009-08-15 02:12:20
【问题描述】:

我正在面板上绘制文件和文件夹名称列表,我正在尝试集思广益来检测用户是否以及何时单击文件/文件夹名称,以及他们实际上是什么文件或文件夹名称点击。

以下是我目前编写的方法。我的第一个想法是使用透明控件来搭载每段文本,并以这种方式动态连接 onclick 事件。但这似乎是一种资源浪费。

private void DisplayFolderContents(ListBox lb, string sPath)
    {
        lblPath.Text = sPath;
        const float iPointX = 01.0f;
        float iPointY = 20.0f;
        DirectoryContents = FileSystem.RetrieveDirectoriesAndFiles(sPath, true, true, "*.mp3");

        foreach (string str in DirectoryContents)
        {
            DrawString(FileSystem.ReturnFolderFromPath(str), iPointX, iPointY, 21, panListing);


            iPointY += 50;
        }
    }


private void DrawString(string textToDraw, float xCoordinate, float yCoordinate, int fontSize, Control controlToDrawOn)
    {

        Graphics formGraphics = controlToDrawOn.CreateGraphics();
        formGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
        Font drawFont = new Font(
                "Arial", fontSize, FontStyle.Bold);

        SolidBrush drawBrush = new
                SolidBrush(Color.White);

        formGraphics.DrawString(textToDraw, drawFont, drawBrush, xCoordinate, yCoordinate);

        drawFont.Dispose();
        drawBrush.Dispose();
        formGraphics.Dispose();
    }

谢谢, 凯文

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    首先,保留一个列表,列出在您的面板上绘制的每个字符串或对象及其位置和大小。

    之后,处理事件 MouseDown 或 MouseUp(取决于你想要的行为)

    List<YourObject> m_list; //The list of objects drawn in the panel.
    
    private void OnMouseDown(object sender, MouseEventArgs e)
    {
        foreach(YourObject obj in m_list)
        {
            if(obj.IsHit(e.X, e.Y))
            {
                //Do Something
            }
        }
    }
    

    在YourObject类中实现了IsHit函数:

    public class YourObject
    {
    
        public Point Location { get; set; }
        public Size Size {get; set; }
    
        public bool IsHit(int x, int y)
        {
            Rectangle rc = new Rectangle(this.Location, this.Size);
            return rc.Contains(x, y);
        }
    }
    

    不必每次都创建矩形,你可以有一个类变量来保存这些信息。当位置或大小发生变化时更新矩形很重要。

    【讨论】:

    • 谢谢。这确实回答了我提出的问题。
    • 如果对象是椭圆怎么办?
    【解决方案2】:

    我知道我错过了一个明显的解决方案。我可以将文本绘制到按钮或其他控件上,然后以这种方式连接起来。呵呵!

    【讨论】:

    • 这是一种更好的方法,因为您可以使用控件分层来为您处理 z 顺序。
    • 这与“我的第一个想法是用透明控件搭载每段文本并以这种方式动态连接 onclick 事件有什么不同。但这似乎是一种资源浪费。” ?
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多