我將不勝感激將按鈕的顏色更改為剛剛按下的不同按鈕的顏色的幫助。我有兩個由以下定義的按鈕陣列:
public partial class Form1 : Form
{
Button[,] btn = new Button[8, 8];
Button[,] btn2 = new Button[10, 20];
public Form1()
{
InitializeComponent();
for (int x = 0; x < btn.GetLength(0); x )
{
for (int y = 0; y < btn.GetLength(1); y )
{
btn[x, y] = new Button();
btn[x, y].SetBounds(40 * x, 40 * y, 40, 40);
btn[x, y].Click = new EventHandler(this.btnEvent_click);
Controls.Add(btn[x, y]);
btn[x, y].BackColor = Color.Empty;
}
}
for (int v = 0; v < btn2.GetLength(0); v )
{
for (int w = 0; w < btn2.GetLength(1); w )
{
btn2[v, w] = new Button();
btn2[v, w].SetBounds(40 * v, 40 * w, 40, 40);
btn2[v, w].Click = new EventHandler(this.btn2Event_click);
Controls.Add(btn2[v, w]);
btn2[v, w].BackColor = Color.Empty;
}
}
btn2我可以使用以下方法更改(從 中選擇按鈕后)中任何按鈕的顏色btn:
void btnEvent_click(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.FromName(buttonColor.colorResult);
}
void btn2Event_click(object sender, EventArgs e)
{
string selectedColor = "";
selectedColor = btn2[0,0].BackColor.ToString();
int pFrom = selectedColor.IndexOf("[") "[".Length;
int pTo = selectedColor.LastIndexOf("]");
buttonColor.colorResult = selectedColor.Substring(pFrom, pTo - pFrom);
}
但正如你所見,它只是btn2[0,0]. 我正在尋找一種方法來使我在其中按下的任何按鈕都可以使用btn2。
uj5u.com熱心網友回復:
在控制元件中的事件中,sender通常是您剛剛與之互動的確切控制元件。在您的情況下,沒有跡象表明 i 并不總是您剛剛單擊的按鈕。然后,您需要做的就是將物件轉換回您知道的型別。因此,在沒有任何例外檢查的情況下,這是一個可行的示例
void btn2Event_click(object sender, EventArgs e)
{
// get the sender as a button
Button button = ((Button)sender);
string selectedColor = button.BackColor.ToString();
int pFrom = selectedColor.IndexOf("[") "[".Length;
int pTo = selectedColor.LastIndexOf("]");
buttonColor.colorResult = selectedColor.Substring(pFrom, pTo - pFrom);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/418011.html
標籤:
