如何在窗口启动时突出显示文本框中的文本

本文关键字:文本 显示 窗口 启动 | 更新日期: 2023-09-27 18:10:29

几天前我在这里问过一个类似的问题。除了在窗口启动时执行相同的操作外,答案工作得很好。这意味着我需要在每次打开窗口时突出显示textBox中的文本。

目前,我在启动时将焦点设置为textBox,在构造函数中没有问题。话虽如此,我猜测执行此操作的正确区域是在构造函数中。这是我目前正在尝试的,没有运气:

public AddDestination()
{
     InitializeComponent();
     //Give cursor focus to the textbox
     destination_textBox.Focus();
     //Highlights text **DOES NOT WORK
     destination_textBox.SelectionStart = 0;
     destination_textBox.SelectionLength = destination_textBox.Text.Length;
}

我怎样才能使我的textBox内的文本在窗口打开时突出显示?

如何在窗口启动时突出显示文本框中的文本

将其移动到AddDestination_Load事件中,而不是构造函数。

     public AddDestination()
    {
        InitializeComponent();
    }
    private void AddDestination_Load(object sender, EventArgs e)
    {
        //Give cursor focus to the textbox
        textBox1.Focus();
        //Highlights text **DOES NOT WORK
        textBox1.SelectionStart = 0;
        textBox1.SelectionLength = textBox1.Text.Length;
    }

可以在Load EventHandler

中编写这段代码
//code
InitializeComponent();
//code
private void Form_Load(object sender, EventArgs e)
{
     //Give cursor focus to the textbox
     destination_textBox.Focus();
     //Highlights text **DOES NOT WORK
     destination_textBox.SelectionStart = 0;
     destination_textBox.SelectionLength = destination_textBox.Text.Length;
}

进入Designer,点击窗口,进入Properties,点击Events按钮,搜索Load event然后双击。