Windows C#窗体:提示将焦点集中在文本框上

本文关键字:集中 文本 焦点 窗体 提示 Windows | 更新日期: 2023-09-27 17:59:29

我想知道在使用"窗口提示"窗体时如何自动选择文本框。下面的代码显示了我尝试过的内容,但它仍然专注于按钮而不是文本框。提前感谢您的帮助和帮助。

            Form prompt = new Form();
            prompt.Width = 500;
            prompt.Height = 200;
            prompt.Text = caption;
            Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
            TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
            Button confirmation = new Button() { Text = "Ok", Left = 50, Width = 100, Top = 90 };
            confirmation.Click += (sender, e) => { prompt.Close(); };
            textBox.Select();
            textBox.Focus();
            prompt.Controls.Add(confirmation);
            prompt.Controls.Add(textLabel);
            prompt.Controls.Add(textBox);
            prompt.ShowDialog();
            return textBox.Text;

Windows C#窗体:提示将焦点集中在文本框上

您需要等待文本框聚焦,直到显示表单。在表单首次显示之前,无法集中任何内容。您可以在表单首次显示后使用Shown事件来执行一些代码。

string text = "Text";
string caption = "caption";
Form prompt = new Form();
prompt.Width = 500;
prompt.Height = 200;
prompt.Text = caption;
Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
Button confirmation = new Button() { Text = "Ok", Left = 50, Width = 100, Top = 90 };
confirmation.Click += (s, e) => { prompt.Close(); };
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.Shown += (s, e) => textBox.Focus();
prompt.ShowDialog();
return textBox.Text;