简体   繁体   中英

Why does ShowDialog select text in my TextBox?

I have a very simple error popup I'm trying to make. When I call ShowDialog, all the text in the textbox gets selected. It looks silly. When I break right before ShowDialog, no text is selected. After the call to ShowDialog, all the text is selected without any user interaction.

    static void ShowError(string error)
    {
        var form = new Form
        {
            Text = "Unexpected Error",
            Size = new System.Drawing.Size(800, 600),
            StartPosition = FormStartPosition.CenterParent,
            ShowIcon = false,
            MinimizeBox = false,
            MaximizeBox = false
        };

        var textBox = new TextBox
        {
            Text = error,
            Dock = DockStyle.Fill,
            Multiline = true,
            ReadOnly = true,
        };

        form.Controls.Add(textBox);
        form.ShowDialog();
    }

您可以将SelectionStart=0, SelectionLength = 0Enabled = false到您的文本框创建代码中

Well, if you set TabStop=false; the control will be deselected. However, ReadOnly means that your user could always select text manually.

FROM MSDN - . With the property set to true, users can still scroll and highlight text in a text box without allowing changes. . With the property set to true, users can still scroll and highlight text in a text box without allowing changes.

Try setting SelectionStart explicitly, though I'm not sure why this is necessary:

static void ShowError(string error)
{
    var form = new Form
    {
        Text = "Unexpected Error",
        Size = new System.Drawing.Size(800, 600),
        StartPosition = FormStartPosition.CenterParent,
        ShowIcon = false,
        MinimizeBox = false,
        MaximizeBox = false
    };

    form.SuspendLayout();
    var textBox = new TextBox
    {
        Text = error,
        Name = "textBox1",
        Dock = DockStyle.Fill,
        Multiline = true,
        ReadOnly = true,
        SelectionStart = 0, // or = error.Length if you prefer
    };

    form.Controls.Add(textBox);
    form.ResumeLayout();
    form.PerformLayout();
    form.ShowDialog();
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM