2013-02-15 64 views
1

我在想如何在Windows窗体上使用提示时自动选​​择文本框。我的代码如下所示显示了我所尝试的内容,但它仍然关注按钮而不是文本框。提前感谢您的帮助和帮助。Windows C#窗体:关注文本框

  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; 

回答

4

您需要等待将文本框对焦到表单显示后。第一次显示表格之前,并非能够将聚焦于任何事物。首次显示表单后,您可以使用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; 
+0

没关系它的工作原理!谢谢!虐待接受你的答案不久 – AustinT 2013-02-15 20:16:12

+0

@AustinTruong你是正确的,请参阅编辑(这次我测试了它)。 – Servy 2013-02-15 20:20:36