-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCheckedComboBox.cs
More file actions
409 lines (356 loc) · 18.6 KB
/
CheckedComboBox.cs
File metadata and controls
409 lines (356 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
namespace CheckComboBoxTest {
public class CheckedComboBox : ComboBox {
/// <summary>
/// Internal class to represent the dropdown list of the CheckedComboBox
/// </summary>
internal class Dropdown : Form {
// ---------------------------------- internal class CCBoxEventArgs --------------------------------------------
/// <summary>
/// Custom EventArgs encapsulating value as to whether the combo box value(s) should be assignd to or not.
/// </summary>
internal class CCBoxEventArgs : EventArgs {
private bool assignValues;
public bool AssignValues {
get { return assignValues; }
set { assignValues = value; }
}
private EventArgs e;
public EventArgs EventArgs {
get { return e; }
set { e = value; }
}
public CCBoxEventArgs(EventArgs e, bool assignValues) : base() {
this.e = e;
this.assignValues = assignValues;
}
}
// ---------------------------------- internal class CustomCheckedListBox --------------------------------------------
/// <summary>
/// A custom CheckedListBox being shown within the dropdown form representing the dropdown list of the CheckedComboBox.
/// </summary>
internal class CustomCheckedListBox : CheckedListBox {
private int curSelIndex = -1;
public CustomCheckedListBox() : base() {
this.SelectionMode = SelectionMode.One;
this.HorizontalScrollbar = true;
}
/// <summary>
/// Intercepts the keyboard input, [Enter] confirms a selection and [Esc] cancels it.
/// </summary>
/// <param name="e">The Key event arguments</param>
protected override void OnKeyDown(KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
// Enact selection.
((CheckedComboBox.Dropdown) Parent).OnDeactivate(new CCBoxEventArgs(null, true));
e.Handled = true;
} else if (e.KeyCode == Keys.Escape) {
// Cancel selection.
((CheckedComboBox.Dropdown) Parent).OnDeactivate(new CCBoxEventArgs(null, false));
e.Handled = true;
} else if (e.KeyCode == Keys.Delete) {
// Delete unckecks all, [Shift + Delete] checks all.
for (int i = 0; i < Items.Count; i++) {
SetItemChecked(i, e.Shift);
}
e.Handled = true;
}
// If no Enter or Esc keys presses, let the base class handle it.
base.OnKeyDown(e);
}
protected override void OnMouseMove(MouseEventArgs e) {
base.OnMouseMove(e);
int index = IndexFromPoint(e.Location);
Debug.WriteLine("Mouse over item: " + (index >= 0 ? GetItemText(Items[index]) : "None"));
if ((index >= 0) && (index != curSelIndex)) {
curSelIndex = index;
SetSelected(index, true);
}
}
} // end internal class CustomCheckedListBox
// --------------------------------------------------------------------------------------------------------
// ********************************************* Data *********************************************
private CheckedComboBox ccbParent;
// Keeps track of whether checked item(s) changed, hence the value of the CheckedComboBox as a whole changed.
// This is simply done via maintaining the old string-representation of the value(s) and the new one and comparing them!
private string oldStrValue = "";
public bool ValueChanged {
get {
string newStrValue = ccbParent.Text;
if ((oldStrValue.Length > 0) && (newStrValue.Length > 0)) {
return (oldStrValue.CompareTo(newStrValue) != 0);
} else {
return (oldStrValue.Length != newStrValue.Length);
}
}
}
// Array holding the checked states of the items. This will be used to reverse any changes if user cancels selection.
bool[] checkedStateArr;
// Whether the dropdown is closed.
private bool dropdownClosed = true;
private CustomCheckedListBox cclb;
public CustomCheckedListBox List {
get { return cclb; }
set { cclb = value; }
}
// ********************************************* Construction *********************************************
public Dropdown(CheckedComboBox ccbParent) {
this.ccbParent = ccbParent;
InitializeComponent();
this.ShowInTaskbar = false;
// Add a handler to notify our parent of ItemCheck events.
this.cclb.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.cclb_ItemCheck);
}
// ********************************************* Methods *********************************************
// Create a CustomCheckedListBox which fills up the entire form area.
private void InitializeComponent() {
this.cclb = new CustomCheckedListBox();
this.SuspendLayout();
//
// cclb
//
this.cclb.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.cclb.Dock = System.Windows.Forms.DockStyle.Fill;
this.cclb.FormattingEnabled = true;
this.cclb.Location = new System.Drawing.Point(0, 0);
this.cclb.Name = "cclb";
this.cclb.Size = new System.Drawing.Size(47, 15);
this.cclb.TabIndex = 0;
//
// Dropdown
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Menu;
this.ClientSize = new System.Drawing.Size(47, 16);
this.ControlBox = false;
this.Controls.Add(this.cclb);
this.ForeColor = System.Drawing.SystemColors.ControlText;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MinimizeBox = false;
this.Name = "ccbParent";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.ResumeLayout(false);
}
public string GetCheckedItemsStringValue() {
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < cclb.CheckedItems.Count; i++) {
sb.Append(cclb.GetItemText(cclb.CheckedItems[i])).Append(ccbParent.ValueSeparator);
}
if (sb.Length > 0) {
sb.Remove(sb.Length - ccbParent.ValueSeparator.Length, ccbParent.ValueSeparator.Length);
}
return sb.ToString();
}
/// <summary>
/// Closes the dropdown portion and enacts any changes according to the specified boolean parameter.
/// NOTE: even though the caller might ask for changes to be enacted, this doesn't necessarily mean
/// that any changes have occurred as such. Caller should check the ValueChanged property of the
/// CheckedComboBox (after the dropdown has closed) to determine any actual value changes.
/// </summary>
/// <param name="enactChanges"></param>
public void CloseDropdown(bool enactChanges) {
if (dropdownClosed) {
return;
}
Debug.WriteLine("CloseDropdown");
// Perform the actual selection and display of checked items.
if (enactChanges) {
ccbParent.SelectedIndex = -1;
// Set the text portion equal to the string comprising all checked items (if any, otherwise empty!).
ccbParent.Text = GetCheckedItemsStringValue();
} else {
// Caller cancelled selection - need to restore the checked items to their original state.
for (int i = 0; i < cclb.Items.Count; i++) {
cclb.SetItemChecked(i, checkedStateArr[i]);
}
}
// From now on the dropdown is considered closed. We set the flag here to prevent OnDeactivate() calling
// this method once again after hiding this window.
dropdownClosed = true;
// Set the focus to our parent CheckedComboBox and hide the dropdown check list.
ccbParent.Focus();
this.Hide();
// Notify CheckedComboBox that its dropdown is closed. (NOTE: it does not matter which parameters we pass to
// OnDropDownClosed() as long as the argument is CCBoxEventArgs so that the method knows the notification has
// come from our code and not from the framework).
ccbParent.OnDropDownClosed(new CCBoxEventArgs(null, false));
}
protected override void OnActivated(EventArgs e) {
Debug.WriteLine("OnActivated");
base.OnActivated(e);
dropdownClosed = false;
// Assign the old string value to compare with the new value for any changes.
oldStrValue = ccbParent.Text;
// Make a copy of the checked state of each item, in cace caller cancels selection.
checkedStateArr = new bool[cclb.Items.Count];
for (int i = 0; i < cclb.Items.Count; i++) {
checkedStateArr[i] = cclb.GetItemChecked(i);
}
}
protected override void OnDeactivate(EventArgs e) {
Debug.WriteLine("OnDeactivate");
base.OnDeactivate(e);
CCBoxEventArgs ce = e as CCBoxEventArgs;
if (ce != null) {
CloseDropdown(ce.AssignValues);
} else {
// If not custom event arguments passed, means that this method was called from the
// framework. We assume that the checked values should be registered regardless.
CloseDropdown(true);
}
}
private void cclb_ItemCheck(object sender, ItemCheckEventArgs e) {
if (ccbParent.ItemCheck != null) {
ccbParent.ItemCheck(sender, e);
}
}
} // end internal class Dropdown
// ******************************** Data ********************************
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
// A form-derived object representing the drop-down list of the checked combo box.
private Dropdown dropdown;
// The valueSeparator character(s) between the ticked elements as they appear in the
// text portion of the CheckedComboBox.
private string valueSeparator;
public string ValueSeparator {
get { return valueSeparator; }
set { valueSeparator = value; }
}
public bool CheckOnClick {
get { return dropdown.List.CheckOnClick; }
set { dropdown.List.CheckOnClick = value; }
}
public new string DisplayMember {
get { return dropdown.List.DisplayMember; }
set { dropdown.List.DisplayMember = value; }
}
public new CheckedListBox.ObjectCollection Items {
get { return dropdown.List.Items; }
}
public CheckedListBox.CheckedItemCollection CheckedItems {
get { return dropdown.List.CheckedItems; }
}
public CheckedListBox.CheckedIndexCollection CheckedIndices {
get { return dropdown.List.CheckedIndices; }
}
public bool ValueChanged {
get { return dropdown.ValueChanged; }
}
// Event handler for when an item check state changes.
public event ItemCheckEventHandler ItemCheck;
// ******************************** Construction ********************************
public CheckedComboBox() : base() {
// We want to do the drawing of the dropdown.
this.DrawMode = DrawMode.OwnerDrawVariable;
// Default value separator.
this.valueSeparator = ", ";
// This prevents the actual ComboBox dropdown to show, although it's not strickly-speaking necessary.
// But including this remove a slight flickering just before our dropdown appears (which is caused by
// the empty-dropdown list of the ComboBox which is displayed for fractions of a second).
this.DropDownHeight = 1;
// This is the default setting - text portion is editable and user must click the arrow button
// to see the list portion. Although we don't want to allow the user to edit the text portion
// the DropDownList style is not being used because for some reason it wouldn't allow the text
// portion to be programmatically set. Hence we set it as editable but disable keyboard input (see below).
this.DropDownStyle = ComboBoxStyle.DropDown;
this.dropdown = new Dropdown(this);
// CheckOnClick style for the dropdown (NOTE: must be set after dropdown is created).
this.CheckOnClick = true;
}
// ******************************** Operations ********************************
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
protected override void OnDropDown(EventArgs e) {
base.OnDropDown(e);
DoDropDown();
}
private void DoDropDown() {
if (!dropdown.Visible) {
Rectangle rect = RectangleToScreen(this.ClientRectangle);
dropdown.Location = new Point(rect.X, rect.Y + this.Size.Height);
int count = dropdown.List.Items.Count;
if (count > this.MaxDropDownItems) {
count = this.MaxDropDownItems;
} else if (count == 0) {
count = 1;
}
dropdown.Size = new Size(this.Size.Width, (dropdown.List.ItemHeight) * count + 2);
dropdown.Show(this);
}
}
protected override void OnDropDownClosed(EventArgs e) {
// Call the handlers for this event only if the call comes from our code - NOT the framework's!
// NOTE: that is because the events were being fired in a wrong order, due to the actual dropdown list
// of the ComboBox which lies underneath our dropdown and gets involved every time.
if (e is Dropdown.CCBoxEventArgs) {
base.OnDropDownClosed(e);
}
}
protected override void OnKeyDown(KeyEventArgs e) {
if (e.KeyCode == Keys.Down) {
// Signal that the dropdown is "down". This is required so that the behaviour of the dropdown is the same
// when it is a result of user pressing the Down_Arrow (which we handle and the framework wouldn't know that
// the list portion is down unless we tell it so).
// NOTE: all that so the DropDownClosed event fires correctly!
OnDropDown(null);
}
// Make sure that certain keys or combinations are not blocked.
e.Handled = !e.Alt && !(e.KeyCode == Keys.Tab) &&
!((e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Right) || (e.KeyCode == Keys.Home) || (e.KeyCode == Keys.End));
base.OnKeyDown(e);
}
protected override void OnKeyPress(KeyPressEventArgs e) {
e.Handled = true;
base.OnKeyPress(e);
}
public bool GetItemChecked(int index) {
if (index < 0 || index > Items.Count) {
throw new ArgumentOutOfRangeException("index", "value out of range");
} else {
return dropdown.List.GetItemChecked(index);
}
}
public void SetItemChecked(int index, bool isChecked) {
if (index < 0 || index > Items.Count) {
throw new ArgumentOutOfRangeException("index", "value out of range");
} else {
dropdown.List.SetItemChecked(index, isChecked);
// Need to update the Text.
this.Text = dropdown.GetCheckedItemsStringValue();
}
}
public CheckState GetItemCheckState(int index) {
if (index < 0 || index > Items.Count) {
throw new ArgumentOutOfRangeException("index", "value out of range");
} else {
return dropdown.List.GetItemCheckState(index);
}
}
public void SetItemCheckState(int index, CheckState state) {
if (index < 0 || index > Items.Count) {
throw new ArgumentOutOfRangeException("index", "value out of range");
} else {
dropdown.List.SetItemCheckState(index, state);
// Need to update the Text.
this.Text = dropdown.GetCheckedItemsStringValue();
}
}
} // end public class CheckedComboBox
}