为什么在这个实例中调用Focus()没有设置焦点?

时间:2014-05-23 22:24:11

标签: c# dynamic focus windows-forms-designer

我根据this改编了自己的输入框。

我将代码修改为以下内容:

using System;
using System.Windows.Forms;

public static class PromptForText
{
    public static string ShowDialog(string caption, string text)
    {
        Form prompt = new Form();
        prompt.Width = 280;
        prompt.Height = 150;
        prompt.Text = caption;
        Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
        TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240 };
        Button confirmation = new Button() { Text = "Okie Doak", Left = 16, Width = 80, Top = 72 };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.Controls.Add(textBox);
        prompt.StartPosition = FormStartPosition.CenterScreen;
        prompt.ShowDialog();
        textBox.Focus();
        return textBox.Text;
    }
}

我添加了“textBox.Focus()”,但它没有达到我的预期。我在调用ShowDialog()之前和之后都尝试过它。

我错过了什么?为什么不将焦点集中在文本框集焦点上呢?

更新

基于史蒂夫(沃兹尼亚克的?)答案,现在就像这样创建控件:

TextBox textBox = new TextBox() { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
Button confirmation = new Button() { Text = "Okie Doak", Left = 16, Width = 80, Top = 72, TabIndex = 1, TabStop = true };

3 个答案:

答案 0 :(得分:2)

调用ShowDialog是一个阻塞调用。这意味着在您(或您的用户)关闭表单之前,此调用后不会执行任何代码。此时,对Focus的调用没有任何效果,因为表单虽然仍在内存中,但是已隐藏并准备好关闭和处理。

作为一个简单的解决方法,只需将TextBox的TabIndex属性设置为窗体上的第一个控件即可。通过这种方式,焦点由Forms Framework代码自动处理(还需要将TabStop属性设置为true)

 TextBox textBox = new TextBox() 
          { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };

经过一些测试后,我应该补充一点,你需要在Button控件上设置相同的属性才能让它工作

 Label textLabel = new Label() { Left = 16, Top = 20, Width = 240, Text = text };
 TextBox textBox = new TextBox()
          { Left = 16, Top = 40, Width = 240, TabIndex = 0, TabStop = true };
 Button confirmation = new Button() 
          { Text = "Okie Doak", Left = 16, Width = 80, Top = 72, TabIndex = 1, TabStop = true };

另一种可能性是在添加Button和Label之前将TextBox添加为窗体控件集合中的第一个控件

 prompt.Controls.Add(textBox);
 prompt.Controls.Add(confirmation);
 prompt.Controls.Add(textLabel);

答案 1 :(得分:1)

您的Focus命令仅在ShowDialog完成后才会发生。如果您查看ShowDialog文档 - http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog.aspx

您将看到ShowDialog仅在窗口关闭时完成。

答案 2 :(得分:1)

您的表单仅在致电ShowDialog()期间可见。为什么在ShowDialog()之前设置焦点并不起作用我不确定,但可能在加载和显示表单的过程中,焦点会丢失。至于 ShowDialog()之后的为什么不起作用,到那时表格已被用户显示和关闭。太晚了。要在显示表单之前立即设置焦点,您可以使用包含焦点代码的方法处理prompt.Load