Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c# - how to change the check image on a checkbox

it has text, an image, and then the checkbox,

I want to use a better image for the check, but cannot find a way to change the checked and unchecked images

this.checkBox1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this.checkBox1.Checked = true;
this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox1.Image = global::ClientExam.Properties.Resources.action32;
this.checkBox1.Location = new System.Drawing.Point(145, 140);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(273, 127);
this.checkBox1.TabIndex = 0;
this.checkBox1.Text = "checkBox1";
this.checkBox1.TextImageRelation = System.Windows.Forms.TextImageRelation.TextBeforeImage;
this.checkBox1.UseVisualStyleBackColor = true;

anybody know of one that doesn't require me to write my own control?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For anyone who'd prefer not to override OnPaint, there's an alternative solution:

  1. Add an ImageList control and fill it with images to reflect checked/unchecked states.
  2. Set your Checkbox control's Appearance property to Button (to get rid of standard CheckBox icon)
  3. Set its' FlatStyle property to Flat (so that the control doesn't really look like a button).
    Note: You may want to check its' FlatAppearance group of properties too. Namely CheckedBackColor, MouseDownBackColor, MouseOverBackColor, i.e. set them all to Control value.
  4. Set Checkbox control's ImageList property to the name of your ImageList control.
  5. Set Checkbox control's Imageindex and ImageAlign properties to reflect its' current state.
  6. Last and most importantly set Checkbox control's TextImageRelation property (this value won't let the text and image overlap unless you want them to). I.e. ImageBeforetext value represents common CheckBox icon location.

Now the only thing left to do is to change the image when the state is changed, smth like this:

    private void chkMyCheckBoxWithAnImage_CheckedChanged(object sender, EventArgs e)
    {
        if (chkMyCheckBoxWithAnImage.Checked)
            chkMyCheckBoxWithAnImage.ImageIndex = 1;
        else
            chkMyCheckBoxWithAnImage.ImageIndex = 0;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...