c# TextBox border changes when it gets disabled compared to other disabled TextBox(es)

前端 未结 1 523
无人共我
无人共我 2021-01-14 03:39

I have a really strange problem. I have multiple TextBoxes for username/passwords, and a CheckBox beside every user/pass group. When user clicks on the CheckBox, and if he c

相关标签:
1条回答
  • 2021-01-14 03:50

    So far as I can tell, this is a bug in the way the system is rendering the control's disabled state. I've created the following code to simulate this issue. The code is a bit verbose but I made it so in order easily understand the logic flow.

    I created a form, with : 4 textboxes named txtBox1, txtBox2, txtBox3 and txtBox4 4 checkboxes named chkBox1, chkBox2, chkBox3 and chkBox4

    Set the Enabled property of each textbox to False (I did this at design time)

        private void Form1_Load(object sender, EventArgs e) {
            chkBox1.CheckedChanged += chkBox_CheckedChanged;
            chkBox2.CheckedChanged += chkBox_CheckedChanged;
            chkBox3.CheckedChanged += chkBox_CheckedChanged;
            chkBox4.CheckedChanged += chkBox_CheckedChanged;
        }
    
        private void chkBox_CheckedChanged(object sender, EventArgs e) {
            var chkBox = ((CheckBox)sender);
            var controlSet = chkBox.Name.Substring(6,1);
            var txtName = "txtBox" + controlSet;
    
            foreach (var txtBox in Controls.Cast<object>().Where(ctl => ((Control)ctl).Name == txtName).Select(ctl => ((TextBox)ctl))) {
                if (chkBox.Checked) {
                    txtBox.Enabled = true;
                    txtBox.Focus();
                }
                else {
                    //The checkbox stole the focuse when it was clicked, so no need to change.
                    txtBox.Enabled = false;
                }
            }
        }
    

    Now if you execute this code, you can check the checkboxes to enable the textbox with the same name prefix (1, 2, 3 or 4). This also sets the focus to the Textbox. Now, if you disable a Textbox that has the focus, it shows up differently than other disabled Textboxes.

    I tried all kinds of Refresh, Invalidate, etc.. on the controls and Form itself to no avail.

    UPDATE

    So I found a hack that seems to work. If you set the borderstyle of the textbox to 'None' before disabling, and then reset it afterwards, the odd outline effect doesn't happen.

        var borderStyle = txtBox.BorderStyle;
        txtBox.BorderStyle = BorderStyle.None;
        txtBox.Enabled = false;
        txtBox.BorderStyle = borderStyle;
    
    0 讨论(0)
提交回复
热议问题