簡體   English   中英

如何檢測動態繪制圖形的點擊?

[英]How to detect a click of a dynamically drawn graphic?

我正在繪制一個面板上的文件和文件夾名稱列表,我正在嘗試集思廣益,以檢測用戶是否以及何時單擊文件/文件夾名稱,以及他們實際點擊的文件或文件夾名稱。

以下是我到目前為止所寫的方法。 我的第一個想法是用透明控件捎回每一段文本,並以這種方式動態連接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();
    }

謝謝,凱文

首先,保留面板上繪制的每個字符串或對象的列表及其位置和大小。

之后,處理事件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);
    }
}

沒有必要每次都創建矩形,你可以有一個類變量來保存這些信息。 當位置或大小發生變化時更新矩形非常重要。

我知道我錯過了一個明顯的解決方案。 我可以將文本繪制到按鈕或其他控件上,然后將其連接起來。 衛生署!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM