为什么ShowDialog在我的TextBox中选择文本?

时间:2012-02-25 18:54:21

标签: c# .net winforms

我正在尝试制作一个非常简单的错误弹出窗口。当我调用ShowDialog时,文本框中的所有文本都会被选中。看起来很傻。当我在ShowDialog之前断开时,没有选择任何文本。在调用ShowDialog之后,所有文本都被选中而没有任何用户交互。

    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();
    }

3 个答案:

答案 0 :(得分:3)

您可以在文本框创建代码

中添加SelectionStart=0, SelectionLength = 0Enabled = false

答案 1 :(得分:2)

好吧,如果你设置TabStop = false;控件将被取消选择。但是,ReadOnly意味着您的用户始终可以手动选择文本。

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

答案 2 :(得分:0)

尝试明确设置SelectionStart,但我不确定为什么这是必要的:

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();
}