Pole tláčítek
V WF
private Button1[,] button1 = new Button1[9, 9];
private int x,y;
....
public class Button1 : Button
{
public int x, y;
public Button1(int x, int y)
{
this.x = x;
this.y = y;
}
}
....
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 9; i++)
{
for (int y = 0; y < 9; y++)
{
button1[i, y] = new Button1(i, y);
button1[i, y].MouseDown += new MouseEventHandler(event_MouseDown); //nastaví event
label[i, y].BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
button1[i, y].Location = new Point(i * 50 + 50 + i, y * 50 + 50 + y);
button1[i, y].BackColor = Color.Bisque;
button1[i, y].AutoSize = false;
button1[i, y].BringToFront();
button1[i, y].Size = new System.Drawing.Size(50, 50);
button1[i, y].TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
button1[i, y].Font = new System.Drawing.Font("Microsoft Sans Serif", 30F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.Controls.Add(button1[i, y]);
}
}
}
private void event_MouseDown(object sender, EventArgs e)
{
Button1 souradnice = (Button1)sender;
button1[souradnice.x, souradnice.y].BackColor = Color.Coral;
x = souradnice.x;
y = souradnice.y;
button1[x, y].Text = "?";
}
Takto lze pracovat i s dalšími třídami a eventy.
K odebrání eventu použijeme znaménko mínus.
button1[i, y].MouseDown -= new MouseEventHandler(event_MouseDown); //odebere event
Vymazání celého panelu.
private void btn_Click(object sender, EventArgs e)
{
panel1.Controls.Clear(); //vymaže vše z panelu
Vymazání jednoho buttonů z formu.Pokud z cyklu nevyskočíme a buttonů je víc začne mazání zlobit.
foreach (Control item in panel1.Controls.OfType<ComboBox>())//vymaže ComboBox z panelu
{
panel1.Controls.Remove(item);
break;
}
foreach (Control item in panel1.Controls.OfType<Control>())//vymaže podle jména
{
if (item.Name == "vymaz")
panel1.Controls.Remove(item);
break;
}
Mazání více buttonů.
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i].Name == "button")
{
this.Controls.RemoveAt(i);
i--;
}
}
Označení textu v textBoxu po cliknutí myší.
private System.Windows.Forms.TextBox lastFocus;
...
t.Click += new EventHandler(event_Click);
...
private void event_Click(object sender, EventArgs e)
{
TextBox senderTextBox = sender as TextBox;
if (lastFocus != senderTextBox)
{
senderTextBox.SelectAll();
}
lastFocus = senderTextBox;
}
V WPF
TextBlock tb = new TextBlock();
tb.VerticalAlignment = System.Windows.VerticalAlignment.Top;
tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
tb.Margin= new Thickness(20) ;
tb.Text = "Nápis";
tb.MouseDown += event_MouseDown;//nastaví event
wrapPanel1.Children.Add(tb);
------------------------------------------------------------------------------
private void event_MouseDown(object sender, MouseEventArgs e)
{
text.Text="jde to";
wrapPanel1.Children.Clear(); //smaže wrapPanel
}