2013-08-25 60 views
2

需要將具有背景圖片的UserControl劃分爲多個可點擊的小區域。點擊它們應該簡單地引發一個事件,從而確定圖片的哪個特定區域被點擊。WinForms控件在UserControl中設置可點擊區域

顯而易見的解決方案是使用透明標籤。但是,它們非常閃爍。所以看起來標籤不是爲此目的而設計的,它們需要花費太多時間來加載。

所以我在想如果有更輕的選項存在?從邏輯上「切片」表面。

儘管如此,我還需要一個邊界周圍的邊框。

用戶控件
+0

你必須知道何時停止使用設計,並開始編寫一些代碼。這是這種情況。只需重寫OnMouseUp()方法並計算從e.Location屬性中單擊的「區域」。通過重寫OnPaint()來繪製邊框。 –

回答

3

做:

MouseClick += new System.Windows.Forms.MouseEventHandler(this.UserControl1_MouseClick); 

現在在UserControl1_MouseClick事件做:

private void UserControl1_MouseClick(object sender, MouseEventArgs e) 
    { 
    int x = e.X; 
    int y = e.Y; 
    } 

現在讓我們來劃分用戶控制到10×10面積:

 int xIdx = x/(Width/10); 
    int yIdx = y/(Height/10); 

    ClickOnArea(xIdx, yIdx); 

ClickOnArea方法你只需要決定在每個領域做什麼。也許使用的Action

一個二維數組,作爲邊境做到這一點:

protected override void OnPaint(PaintEventArgs e) 
    { 
    base.OnPaint(e); 

    Graphics g = e.Graphics; 
    Pen p = new Pen(Color.Black); 
    float xIdx = (float)(Width/10.0); 
    float yIdx = (float)(Height/10.0); 

    for (int i = 0; i < 10; i++) 
    { 
     float currVal = yIdx*i; 
     g.DrawLine(p, 0, currVal, Width, currVal); 
    } 

    g.DrawLine(p, 0, Height - 1, Width, Height - 1); 

    for (int j = 0; j < 10; j++) 
    { 
     float currVal = xIdx * j; 
     g.DrawLine(p, currVal, 0, currVal, Height); 
    } 

    g.DrawLine(p, Width - 1, 0, Width - 1, Height); 
    }