简体   繁体   中英

C# Checkbox not gaining focus on Tabstop

I am making a config editor form and have hit a bit of an issue, I put a lot of time into userfriendly and efficient design and therefor want the TabIndex to work perfectly to minimize use of mouse.

My problem is now when I try to tab through the controls I noticed the CheckBox was not gaining focus like if you press it with the mouse, this means I couldn't tab through and change their state directly from keyboard.

How do I make the CheckBox gain focus via TabIndex and TabStop so that I can just press Enter to change its state via the KeyUp event.

Below is a picture of my form, and next to it a picture of the TabIndex as well as a the code taken directly from the Form.Designer.cs class.

在此处输入图片说明

        // 
        // cbxDefaultPublic
        // 
        this.cbxDefaultPublic.AutoSize = true;
        this.cbxDefaultPublic.Location = new System.Drawing.Point(247, 12);
        this.cbxDefaultPublic.Name = "cbxDefaultPublic";
        this.cbxDefaultPublic.Size = new System.Drawing.Size(15, 14);
        this.cbxDefaultPublic.TabIndex = 1;
        this.cbxDefaultPublic.TabStop = true;
        this.cbxDefaultPublic.UseVisualStyleBackColor = true;

Please note that I had a hard time explaining this cause its a bit complicated and didn't know how to explain it so bare over with me if I got a few things wrong.

With the help of the people commenting on my question I was able to get on the right track of what to do and what to search for.
Thanks to Grant Winney, LarsTech and JohnnyBoy for explaining to me how the CheckBox worked and what I needed to look at.

I found out that the CheckBox does not have a public highlight feature so I had to get creative.
What I did was I created a custom CheckBox and well.. might just show you the code :P

public class MyCbx : CheckBox {
    protected override void OnGotFocus(EventArgs e) {
        base.OnGotFocus(e);
        base.OnEnter(e);
        base.OnMouseEnter(e);
    }
    protected override void OnLostFocus(EventArgs e) {
        base.OnLostFocus(e);
        base.OnLeave(e);
        base.OnMouseLeave(e);
    }
    protected override void OnMouseLeave(EventArgs e) {
        if(!this.Focused) {//prevent it from losing highligh if control is in focus
            base.OnMouseLeave(e);
        }
    }
}

So I call the MouseEnter and Leave events when It gain or lose focus, this will make it change to a highlighted state.

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