2009-08-14 69 views
1

我正在繪製文件夾&文件夾名稱列表,我試圖集體討論檢測用戶是否以及何時單擊文件/文件夾名稱以及他們實際單擊的文件或文件夾名稱的最佳方法。如何檢測一個動態繪製圖形的點擊?

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

感謝, 凱文

回答

2

首先,保持每個字符串或對象以及它們的位置和大小的面板上繪製的列表。

之後,處理的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); 
    } 
} 

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

+0

謝謝。這確實回答了我問的問題。 – Kevin 2009-08-14 17:44:10

2

我知道我錯過了一個明顯的解決方案。我可以將文本繪製到一個buttor或其他控件上,並以這種方式將其連接起來。衛生署!

+1

這是一個更好的方法,因爲您可以使用控件分層來爲您處理z順序。 – MusiGenesis 2009-08-14 18:01:56

+0

這與「我的第一個想法是用透明的控件背誦每一段文本並動態地連接一個onclick事件,但它看起來像浪費資源似的。 ? – barlop 2015-12-20 07:11:38