准备工作:
1、在空白窗体上添加 CheckListBox1;
2、添加四个 Button, 并激活 Button1 的 OnClick 事件;
3、激活窗体的 OnCreate 事件.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst; type TForm1 = class(TForm) CheckListBox1: TCheckListBox; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation var b: Byte; {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin CheckListBox1.Items.CommaText := 'A,B,C,D,E,F,G,H'; Button1.Caption := '±£´æ״̬'; Button2.Caption := '»Ö¸´×´Ì¬'; Button3.Caption := 'È«Ñ¡'; Button4.Caption := 'È«²»Ñ¡'; Button1.Tag := 1; Button2.Tag := 2; Button3.Tag := 3; Button4.Tag := 4; Button2.OnClick := Button1.OnClick; Button3.OnClick := Button1.OnClick; Button4.OnClick := Button1.OnClick; end; procedure TForm1.Button1Click(Sender: TObject); var i: Integer; begin if TButton(Sender).Tag = 1 then b := 0; for i := 0 to CheckListBox1.Count - 1 do case TButton(Sender).Tag of 1: if CheckListBox1.Checked[i] then b := b or (1 shl i); 2: CheckListBox1.Checked[i] := Odd(b shr i); 3: CheckListBox1.Checked[i] := True; 4: CheckListBox1.Checked[i] := False; end; end; end.
{ -------------------------------------------------------------------------------- 用集合的方式重新做前一次的例子(窗体设计与测试效果同前): -------------------------------------------------------------------------------- } unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst; type TForm1 = class(TForm) CheckListBox1: TCheckListBox; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation var set1: set of 0..7; {准备用自定义的集合变量 set1 储存下面的 8 种状态} {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin CheckListBox1.Items.CommaText := 'A,B,C,D,E,F,G,H'; Button1.Caption := '保存状态'; Button2.Caption := '恢复状态'; Button3.Caption := '全选';
Button4.Caption := '全不选';
Button1.Tag := 1; Button2.Tag := 2; Button3.Tag := 3; Button4.Tag := 4; Button2.OnClick := Button1.OnClick; Button3.OnClick := Button1.OnClick; Button4.OnClick := Button1.OnClick; end; procedure TForm1.Button1Click(Sender: TObject); var i: Integer; begin if TButton(Sender).Tag = 1 then set1 := []; for i := 0 to CheckListBox1.Count - 1 do case TButton(Sender).Tag of 1: if CheckListBox1.Checked[i] then Include(set1, i); 2: CheckListBox1.Checked[i] := i in set1; 3: CheckListBox1.Checked[i] := True; 4: CheckListBox1.Checked[i] := False; end; end; end.