Skip to content

In some cases, WinForm TextBox Control automatically selects all text by mistake. #5406

@ghost

Description

In some cases, Textbox Control automatically selects all text by mistake.

TextBox Control will automatically select all texts and highlight them when TextBox control gets the focus. But in fact, in some cases, it may not be necessary to select all the text.

If the program is a Log Viewer, or Notepad, it is just a reader that simply displays more than 100,000 characters. It does not need to automatically select all the text when the application is launched.

After starting the application, if the TextBox is the first control, the TextBox will automatically select all the text and highlight them. Usually this is an unnecessary operation.

photo attachment:
001

Reproduced by the following code:

.Net Version:
.net Framework 4.8 and .net 5.0

using System;
using System.Text;
using System.Windows.Forms;

namespace TextBoxFocusTest
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var userControl = new UserControl()
            {
                Dock = DockStyle.Fill,
            };

            var stringBuilder = new StringBuilder();

            for (int n = 0; n < 10000; n++)
                stringBuilder.Append("Sample Text ");

            userControl.Controls.Add(new TextBox()
            {
                Dock = DockStyle.Fill,
                ScrollBars = ScrollBars.Both,
                Multiline = true,
                Text = stringBuilder.ToString()
            });

            var form = new Form()
            {
                StartPosition = FormStartPosition.CenterScreen,
                Text = "Log Viewer",
                Width = 400,
                Height = 400
            };

            form.Controls.Add(userControl);

            Application.Run(form);
        }
    }
}

By viewing the source code on the Microsoft website, the following code will automatically select all the text when the TextBox gains focus.

If the .net can provide a public property, and users determine whether to select all of the text. It will be more flexible.

photo attachment:
002

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions