c# - 为什么在这种情况下调用 Focus() 没有设置焦点?

标签 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 };

最佳答案

调用 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 };

另一种可能性是在添加按钮和标签之前将 TextBox 添加为表单控件集合中的第一个控件

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

关于c# - 为什么在这种情况下调用 Focus() 没有设置焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23839151/

相关文章:

c# - 我们的自定义类数组如何在没有实现 IEnumerable 的情况下与 foreach 一起工作?

java - 如何从网站接收动态变量(android)

qt - QML 焦点如何传播?

matlab - 如何检测文本编辑对象的焦点丢失?

reactjs - 在单击 div 时将焦点设置为输入

c# - 安装 Facebook 5.0.9.0 时未声明架构版本

c# - 正则表达式匹配一组字母数字后跟一组空格,使字符总数固定

C 动态读取字符串并仅接受括号

c# - Unity List.Add 阻止 Android 上的 Sprite 更新

java - 使用变更日志 xml 作为流输入运行 liquibase