c# - Windows C# 表单 : Prompt focus on a textbox

标签 c# winforms

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

            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;

最佳答案

您需要等到表单显示后才能将文本框聚焦。在第一次显示表单之前,它无法聚焦任何内容。您可以使用 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;

关于c# - Windows C# 表单 : Prompt focus on a textbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14902591/

相关文章:

c# - 测试完成后关闭连接

.net - BackgroundWorker线程问题

c# - 放置在 TableLayout 中的停靠控件的大小不会自动小于其创建大小

c# - C#-如何停止使用其他格式的音频文件(不是正在播放的格式)

c# - 使用 XamlRenderingBackgroundTask 呈现不在可视化树中的图像

c# - 如何使代码与 C# 中的 GUI 分离?

c# - 括号还是引号?

c# - 如何处理窗体的 KeyPress 事件?

c# - 带 IDownloadManager 的 Windows 窗体 Webbrowswer 控件

c# - 如何使用自动验证嵌套对象