I create as many dynamic labels as the user wants.
for (int j = 0; j < Nitelik_Counter; j )
{
Label labeltest= new Label();
labeltest.Text = "N - " j.ToString();
labeltest.TextAlign = ContentAlignment.MiddleCenter;
labeltest.Location = new Point(10 j * 70, 10);
}
And I determine their text like "N i.toString()"
for default.
After that, I'm adding this to the form. I want to do is when the form is open and the user double-clicks one of the labels, a rename function will be open like in the Windows os, and when the user presses the enter it must be save. How do I do that?
CodePudding user response:
When you create labels, setup DoubleClick handler like this:
// ...
Label labeltest= new Label();
labeltest.DoubleClick = Label_DoubleClick;
In the handler, you can add temporary TextBox to the form, place it over the original label, wait until the user presses Enter or Escape and then either change the original text or not and remove the textbox, like this:
protected void Label_DoubleClick(object? sender, EventArgs e)
{
if (sender is Label label)
{
var box = new TextBox();
box.Name = "TextField";
box.Text = label.Text;
box.TextAlign = HorizontalAlignment.Center;
box.AutoSize = false;
box.Dock = DockStyle.None;
box.Size = label.Size;
box.Location = this.PointToClient(label.Parent.PointToScreen(label.Location));
box.BackColor = BackColor;
box.PreviewKeyDown = (a, b) => {
if (b.KeyCode == Keys.Escape)
{
box.Parent.Controls.Remove(box);
}
else if (b.KeyCode == Keys.Enter)
{
label.Text = box.Text;
box.Parent.Controls.Remove(box);
}
};
box.LostFocus = (a, b) => { box.Parent?.Controls.Remove(box); };
Controls.Add(box);
Controls.SetChildIndex(box, 0);
box.SelectAll();
box.Focus();
}
}