-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathExtendedListView.cs
1081 lines (941 loc) · 28.6 KB
/
ExtendedListView.cs
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace Menees.Windows.Forms
{
#region Using Directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
#endregion
/// <summary>
/// A custom list view type that exposes methods for auto-sizing and sorting its columns.
/// </summary>
[ToolboxBitmap(typeof(ListView))]
public class ExtendedListView : ListView
{
#region Public Constants
/// <summary>
/// Set ColumnHeader.Width to this to auto-size the column based on the text in the items.
/// </summary>
public const int AutoSizeByData = -1;
/// <summary>
/// Set ColumnHeader.Width to this to auto-size the column based on its header text.
/// </summary>
public const int AutoSizeByHeader = -2;
#endregion
#region Private Data Members
private const int LvmFirst = 0x1000;
private readonly Sorter sorter;
private readonly Dictionary<int, HeaderData> columnNumberToHeaderDataMap = new();
private readonly Dictionary<int, ListViewColumnType> columnNumberToTypeMap = new();
private IComparer? previousSorter;
private int sorterUpdateLevel;
private int capacity;
private bool inDoubleClick;
private bool doubleClickEventFired;
private bool mouseDown;
private Point mouseDownPoint;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance.
/// </summary>
public ExtendedListView()
{
base.FullRowSelect = true;
base.MultiSelect = false;
base.View = View.Details;
base.HideSelection = false;
this.sorter = new Sorter(this);
this.ListViewItemSorter = this.sorter;
}
#endregion
#region Public Properties
/// <summary>
/// Changes the inherited <see cref="ListView.HideSelection"/> property to default to false.
/// </summary>
[DefaultValue(false)]
public new bool HideSelection
{
get
{
return base.HideSelection;
}
set
{
base.HideSelection = value;
}
}
/// <summary>
/// Changes the inherited <see cref="ListView.FullRowSelect"/> property to default to true.
/// </summary>
[DefaultValue(true)]
public new bool FullRowSelect
{
get
{
return base.FullRowSelect;
}
set
{
base.FullRowSelect = value;
}
}
/// <summary>
/// Changes the inherited <see cref="ListView.MultiSelect"/> property to default to false.
/// </summary>
[DefaultValue(false)]
public new bool MultiSelect
{
get
{
return base.MultiSelect;
}
set
{
base.MultiSelect = value;
}
}
/// <summary>
/// Changes the inherited <see cref="ListView.View"/> property to default to "Details".
/// </summary>
[DefaultValue(View.Details)]
public new View View
{
get
{
return base.View;
}
set
{
base.View = value;
}
}
/// <summary>
/// Gets or sets the number of items that space is reserved for.
/// </summary>
/// <remarks>
/// This setting doesn't affect Items.Count. It just tells the
/// Win32 ListView common control to pre-allocate buffers large
/// enough to allow a certain number of items to be added without
/// having to reallocate any internal lists.
/// </remarks>
[DefaultValue(0)]
[Browsable(false)]
public int Capacity
{
get
{
return this.capacity;
}
set
{
if (this.capacity != value)
{
this.capacity = value;
this.SetCapacity();
}
}
}
/// <summary>
/// Returns the number of items that can be fully visible in the control.
/// </summary>
[Browsable(false)]
public int VisibleItemCount
{
get
{
const int LVM_GETCOUNTPERPAGE = LvmFirst + 40;
int result = NativeMethods.SendMessage(this, LVM_GETCOUNTPERPAGE, 0, 0);
return result;
}
}
/// <summary>
/// Gets whether a double-click event handler is currently being executed.
/// </summary>
[Browsable(false)]
public bool InDoubleClick => this.inDoubleClick;
/// <summary>
/// Gets or sets whether the user can change item checkboxes.
/// </summary>
[DefaultValue(true)]
public bool AllowItemCheck { get; set; } = true;
#endregion
#region Public Methods
/// <summary>
/// See <see cref="ListView.BeginUpdate"/>.
/// </summary>
public new void BeginUpdate()
{
base.BeginUpdate();
this.BeginSorterUpdate();
}
/// <summary>
/// See <see cref="ListView.EndUpdate"/>.
/// </summary>
public new void EndUpdate()
{
this.EndSorterUpdate();
base.EndUpdate();
}
/// <summary>
/// Sorts the specified column in ascending order.
/// </summary>
/// <param name="column">The index of the column to sort.</param>
public void SortColumn(int column)
{
this.sorter.Column = column;
this.sorter.Ascending = true;
this.Sort();
}
/// <summary>
/// Sorts the specified column in ascending or descending order.
/// </summary>
/// <param name="column">The index of the column to sort.</param>
/// <param name="ascending">True to sort ascending. False to sort descending.</param>
public void SortColumn(int column, bool ascending)
{
this.sorter.Column = column;
this.sorter.Ascending = ascending;
this.Sort();
}
/// <summary>
/// Sorts using the current ListViewItemSorter.
/// </summary>
/// <remarks>
/// This method adds support for sorting a virtual list view by calling the
/// <see cref="OnVirtualSortColumn"/> method.
/// </remarks>
public new void Sort()
{
if (this.VirtualMode)
{
if (this.VirtualListSize > 0)
{
int column = this.sorter.Column;
bool ascending = this.sorter.Ascending;
// Save off the selected and focused items.
ListViewItem? focusedItem = null;
int numSelectedItems = this.SelectedIndices.Count;
ListViewItem[] selectedItems = new ListViewItem[numSelectedItems];
for (int i = 0; i < numSelectedItems; i++)
{
ListViewItem item = this.Items[this.SelectedIndices[i]];
selectedItems[i] = item;
if (item.Focused)
{
focusedItem = item;
}
}
this.BeginUpdate();
try
{
this.SelectedIndices.Clear();
this.OnVirtualSortColumn(column, ascending, this.GetColumnType(column));
// If there's only one selected item, then make sure it is visible.
bool ensureVisible = selectedItems.Length == 1;
// Now that the list is sorted, restore the selected items.
foreach (ListViewItem item in selectedItems)
{
// Unfortunately, in a virtual list view, we have no way to
// know the current index for a ListViewItem now that the
// sort of the backing items has occurred. Calling ListViewItem's
// Index property will just return the previous index. So
// we have to call a virtual method that a derived class can
// overload to return the index of where the backing item
// really is in the list now.
//
// A derived list can quickly do an IndexOf in its own collection
// of objects. If we tried to do that on the Items collection,
// it would have to do a RetrieveVirtualItem request for every
// ListViewItem, which would defeat the purpose of using a
// a virtual listview.
int newIndex = this.IndexOf(item);
ListViewItem newItem = this.Items[newIndex];
newItem.Selected = true;
if (item == focusedItem)
{
newItem.Focused = true;
}
if (ensureVisible)
{
newItem.EnsureVisible();
}
}
}
finally
{
this.EndUpdate();
}
}
}
else
{
base.Sort();
}
}
/// <summary>
/// This returns the column width even inside of a BeginUpdate/EndUpdate pair.
/// </summary>
public int GetActualColumnWidth(ColumnHeader header)
{
Conditions.RequireReference(header, nameof(header));
const int LVM_GETCOLUMNWIDTH = LvmFirst + 29;
int result = NativeMethods.SendMessage(this, LVM_GETCOLUMNWIDTH, header.Index, 0);
return result;
}
/// <summary>
/// Auto-sizes the column to fit both the header and data text. This will grow or shrink the column as necessary.
/// </summary>
/// <param name="column">The column to auto-size.</param>
public void AutoSizeColumn(ColumnHeader column)
{
this.AutoSizeColumn(column, true);
}
/// <summary>
/// Auto-sizes the column to fit both the header and data text.
/// </summary>
/// <param name="column">The column to auto-size.</param>
/// <param name="allowShrinking">Whether the column should be allowed to get smaller.</param>
public void AutoSizeColumn(ColumnHeader column, bool allowShrinking)
{
Conditions.RequireReference(column, nameof(column));
this.BeginUpdate();
try
{
int originalWidth = column.Width;
// Only auto-size the header if it is showing.
int headerWidth = 0;
if (this.HeaderStyle != ColumnHeaderStyle.None)
{
bool autoSizeHeader = false;
// Only do the Header auto-size the first time and when the column name or position changes.
if (!this.columnNumberToHeaderDataMap.TryGetValue(column.Index, out HeaderData? data))
{
data = new HeaderData(column.Text);
this.columnNumberToHeaderDataMap.Add(column.Index, data);
autoSizeHeader = true;
}
else if (column.Index == this.Columns.Count - 1)
{
// The AutoSizeByHeader logic for the last column
// will size the header to fit the remaining width,
// so we always want to use it because the control
// or one of the other columns may have changed size
// (possibly by a means we can't detect, like someone
// set Column.Width directly).
autoSizeHeader = true;
data.IsLastColumn = true;
}
else if (column.Index != this.Columns.Count - 1 && data.IsLastColumn)
{
// The column used to be the last column, but now it isn't.
// So we need to resize it because AutoSizeByHeader
// probably made it take up all the remaining width before,
// and now it shouldn't do that.
autoSizeHeader = true;
data.IsLastColumn = false;
}
else if (data.Name != column.Text)
{
autoSizeHeader = true;
data.Name = column.Text;
}
if (autoSizeHeader)
{
column.Width = AutoSizeByHeader;
data.AutoHeaderWidth = this.GetActualColumnWidth(column);
}
headerWidth = data.AutoHeaderWidth;
}
// Since the data width is usually larger than the header text width,
// we'll do it last since we'll probably end up keeping the data width.
int contentWidth = 0;
if (this.Items.Count > 0)
{
column.Width = AutoSizeByData;
contentWidth = this.GetActualColumnWidth(column);
// This is a bug workaround for XP's "themed" ListView. It sizes the
// first column slightly too small when no images are used with the
// control. It doesn't do that when "themes" are turned off.
if (column.Index == 0 && WindowsUtility.AreVisualStylesEnabled && this.SmallImageList == null)
{
contentWidth += SystemInformation.SmallIconSize.Width / 2;
}
}
int newWidth = Math.Max(headerWidth, contentWidth);
if (!allowShrinking && newWidth < originalWidth)
{
// Set the column width back to what it was.
column.Width = originalWidth;
}
else if (newWidth != column.Width)
{
column.Width = newWidth;
}
}
finally
{
this.EndUpdate();
}
}
/// <summary>
/// Auto-sizes all columns.
/// </summary>
public void AutoSizeColumns()
{
this.BeginUpdate();
try
{
foreach (ColumnHeader column in this.Columns)
{
this.AutoSizeColumn(column);
}
}
finally
{
this.EndUpdate();
}
}
/// <summary>
/// Inserts a range of items at the specified index.
/// </summary>
/// <param name="index">The index to start the insertion at.</param>
/// <param name="items">The array of items to insert.</param>
public void InsertRange(int index, ListViewItem[] items)
{
this.InsertRange(index, items, false);
}
/// <summary>
/// Inserts a range of items at the specified index optionally
/// in reverse order.
/// </summary>
/// <param name="index">The index to start the insertion at.</param>
/// <param name="items">The array of items to insert.</param>
/// <param name="reverseOrder">Whether the items should be inserted in reverse order.</param>
public void InsertRange(int index, ListViewItem[] items, bool reverseOrder)
{
this.BeginSorterUpdate();
try
{
int numItems = items.Length;
this.Capacity = this.Items.Count + numItems;
if (reverseOrder)
{
for (int i = 0; i < numItems; i++)
{
this.Items.Insert(index + i, items[numItems - 1 - i]);
}
}
else
{
for (int i = 0; i < numItems; i++)
{
this.Items.Insert(index + i, items[i]);
}
}
}
finally
{
this.EndSorterUpdate();
}
}
/// <summary>
/// Saves the list contents to a tab-separated text file.
/// </summary>
/// <param name="fileName">The name of the file to save to.</param>
public void SaveAsText(string fileName)
{
this.SaveAsText(fileName, "\t");
}
/// <summary>
/// Saves the list contents to a token-separated text file.
/// </summary>
/// <param name="fileName">The name of the file to save to.</param>
/// <param name="separator">The separator string to put between each value in a row.</param>
public void SaveAsText(string fileName, string separator)
{
using (StreamWriter writer = File.CreateText(fileName))
{
this.GetAsText(separator, true, this.Items, writer);
}
}
/// <summary>
/// Gets the list view data for all items as text.
/// </summary>
/// <param name="separator">The separator string to put between each value in a row.</param>
/// <param name="includeHeaders">Whether the column headers should be included.</param>
/// <returns>The text representation of the list view.</returns>
public string GetAsText(string separator, bool includeHeaders)
{
using (StringWriter writer = new())
{
this.GetAsText(separator, includeHeaders, this.Items, writer);
string result = writer.ToString();
return result;
}
}
/// <summary>
/// Gets the list view data for the selected items as text.
/// </summary>
/// <param name="separator">The separator string to put between each value in a row.</param>
/// <param name="includeHeaders">Whether the column headers should be included.</param>
/// <param name="items">The collection of ListViewItems to write.</param>
/// <param name="writer">The text writer to append to.</param>
public void GetAsText(string separator, bool includeHeaders, IEnumerable<ListViewItem> items, TextWriter writer)
{
Conditions.RequireReference(items, nameof(items));
Conditions.RequireReference(writer, nameof(writer));
this.GetAsText(separator, includeHeaders, (IEnumerable)items, writer);
}
/// <summary>
/// Informs the ListView that you've initially populated it with a column in pre-sorted order.
/// </summary>
/// <remarks>
/// If you load a list in order, then this method allows you to tell the ListView control about
/// the pre-existing sort order without having to incur the overhead of an explicit <see cref="Sort"/>
/// operation. Then when a user clicks on the header for the sorted column it can swap the
/// sort order instead of just re-sorting into the same order.
/// </remarks>
/// <param name="column">The column that the list entries are already sorted by.</param>
/// <param name="ascending">True if the column is sorted in ascending order. False if it is in descending order.</param>
public void SetPresortedOrder(int column, bool ascending)
{
this.sorter.Column = column;
this.sorter.Ascending = ascending;
}
/// <summary>
/// Sets the column type for the specified column. This is used for sorting.
/// </summary>
/// <param name="column">The column index.</param>
/// <param name="columnType">The column type.</param>
public void SetColumnType(int column, ListViewColumnType columnType)
{
this.columnNumberToTypeMap[column] = columnType;
}
#endregion
#region Protected Methods
/// <summary>
/// Determines the given column's type.
/// </summary>
/// <param name="column">The index of the column.</param>
/// <returns>The column's type.</returns>
/// <remarks>
/// By default, this assumes it is numeric if it is right-aligned,
/// which works for most cases. Derived classes can change
/// this behavior if necessary by overriding this function.
/// </remarks>
protected internal virtual ListViewColumnType GetColumnType(int column)
{
if (!this.columnNumberToTypeMap.TryGetValue(column, out ListViewColumnType result))
{
result = this.Columns[column].TextAlign == HorizontalAlignment.Right ? ListViewColumnType.Number : ListViewColumnType.String;
}
return result;
}
/// <summary>
/// Compares two <see cref="ListViewItem"/> instances during a sort.
/// </summary>
/// <param name="itemX">The left-hand item to compare.</param>
/// <param name="itemY">The right-hand item to compare.</param>
/// <param name="column">The column to compare for.</param>
/// <param name="ascending">Whether an ascending or decending sort is being done.</param>
/// <param name="columnType">The column's type based on the result of <see cref="GetColumnType"/>.</param>
/// <returns>-1 if ItemX is less than ItemY. 0 if they're equal. 1 if ItemX is greater than ItemY.</returns>
protected internal virtual int CompareItems(ListViewItem itemX, ListViewItem itemY, int column, bool ascending, ListViewColumnType columnType)
{
// For strings this does a case-insensitive comparison.
// For numeric columns this does a double comparison.
// For dates this does a date comparision.
// Derived classes can change this behavior if necessary
// by overriding this function.
// Note: Sometimes, not all of the SubItems are populated.
string textX;
if (column < itemX.SubItems.Count)
{
textX = itemX.SubItems[column].Text;
}
else
{
textX = string.Empty;
columnType = ListViewColumnType.String;
}
string textY;
if (column < itemY.SubItems.Count)
{
textY = itemY.SubItems[column].Text;
}
else
{
textY = string.Empty;
columnType = ListViewColumnType.String;
}
int result;
switch (columnType)
{
case ListViewColumnType.Number:
double doubleX, doubleY;
if (double.TryParse(textX, out doubleX) && double.TryParse(textY, out doubleY))
{
result = Math.Sign(doubleX - doubleY);
break;
}
else
{
goto default;
}
case ListViewColumnType.DateTime:
DateTime dateTimeX, dateTimeY;
if (DateTime.TryParse(textX, out dateTimeX) && DateTime.TryParse(textY, out dateTimeY))
{
result = dateTimeX.CompareTo(dateTimeY);
break;
}
else
{
goto default;
}
default:
result = string.Compare(textX, textY, StringComparison.OrdinalIgnoreCase);
break;
}
if (!ascending)
{
result = -result;
}
return result;
}
/// <summary>
/// Called from a virtual listview (i.e., <see cref="ListView.VirtualMode"/> is true) when a column header is clicked
/// or when <see cref="SortColumn(int, bool)"/> is called.
/// </summary>
/// <remarks>
/// You should not call this method from an override in a derived class. All it does is throw an exception
/// saying that the derived class needs to provide the implementation for it.
/// </remarks>
/// <param name="column">The column to sort.</param>
/// <param name="ascending">Whether an ascending or decending sort should be done.</param>
/// <param name="columnType">The column's type based on the result of <see cref="GetColumnType"/>.</param>
protected virtual void OnVirtualSortColumn(int column, bool ascending, ListViewColumnType columnType)
{
throw Exceptions.NewInvalidOperationException(
"A sort was requested on a virtual ListView, but the list didn't override the OnVirtualSortColumn method.");
}
/// <summary>
/// Overriden to sort the column in a toggling manner like Explorer does.
/// </summary>
/// <param name="e"></param>
protected override void OnColumnClick(ColumnClickEventArgs e)
{
bool ascending = true;
// Toggle the sort direction if they clicked the currently sorted column.
if (this.sorter.Column != -1 && e.Column == this.sorter.Column)
{
ascending = !this.sorter.Ascending;
}
this.SortColumn(e.Column, ascending);
base.OnColumnClick(e);
}
/// <summary>
/// Overriden to set the capacity if necessary.
/// </summary>
/// <param name="e"></param>
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
this.SetCapacity();
}
/// <summary>
/// Processes Windows messages.
/// </summary>
/// <param name="m">The Windows message to process.</param>
protected override void WndProc(ref Message m)
{
// We need to change three things about the default ListView's double-click behavior:
// 1. We don't want double-clicks to cause items to be checked/unchecked.
// 2. We want the event to fire even if they click in the whitespace (i.e. not on an item).
// 3. We don't want the event to fire again after a double-click launches a modal, that
// gets closed, and then someone tries to check or uncheck the item. Somehow in
// .NET 1.0 that sends a WM_LBUTTONUP message and fires the OnDoubleClick override!
const int WM_LBUTTONDBLCLK = 0x0203;
if (m.Msg == WM_LBUTTONDBLCLK)
{
this.doubleClickEventFired = false;
this.inDoubleClick = true;
try
{
base.WndProc(ref m);
}
finally
{
this.inDoubleClick = false;
}
if (!this.doubleClickEventFired)
{
this.doubleClickEventFired = true;
base.OnDoubleClick(EventArgs.Empty);
}
this.doubleClickEventFired = false;
}
else
{
base.WndProc(ref m);
}
}
/// <summary>
/// Called when a double-click event occurs.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnDoubleClick(EventArgs e)
{
if (this.inDoubleClick)
{
this.doubleClickEventFired = true;
base.OnDoubleClick(e);
}
}
/// <summary>
/// Called when an item is checked.
/// </summary>
/// <param name="ice">The event args.</param>
protected override void OnItemCheck(ItemCheckEventArgs ice)
{
bool callBaseImplementation = true;
// Don't let double click change the check state.
// Also, don't let mouse multi-selection change the
// check states.
if (!this.AllowItemCheck || this.inDoubleClick)
{
ice.NewValue = ice.CurrentValue;
callBaseImplementation = false;
}
else if (this.mouseDown && this.SelectedIndices.Count > 1)
{
// Only allow a mouse click to change multiple checks
// if they clicked on one item. If they changed items,
// this works around a ListView bug.
ListViewItem mouseDownItem = this.GetItemAt(this.mouseDownPoint.X, this.mouseDownPoint.Y);
Point currentPoint = this.PointToClient(Control.MousePosition);
ListViewItem currentMouseItem = this.GetItemAt(currentPoint.X, currentPoint.Y);
// The list view also has a bug where it will do item checks
// during multi-selection with Ctrl+Click.
if (mouseDownItem != currentMouseItem || !this.IsPointInCheck(currentPoint, ice.Index))
{
ice.NewValue = ice.CurrentValue;
callBaseImplementation = false;
}
}
if (callBaseImplementation)
{
base.OnItemCheck(ice);
}
}
/// <summary>
/// Called when a mouse button is pressed.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseDown(MouseEventArgs e)
{
this.Capture = true;
this.mouseDown = true;
this.mouseDownPoint = new Point(e.X, e.Y);
}
/// <summary>
/// Called when a mouse button is released.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseUp(MouseEventArgs e)
{
this.Capture = false;
this.mouseDown = false;
}
/// <summary>
/// Used to find the new index for a ListViewItem after a sort
/// or any other operation that changes the virtual collection
/// of items.
/// </summary>
/// <remarks>
/// A derived class should override this to do an IndexOf on its
/// own collection of objects associated with the listview items.
/// <p/>
/// The Index property of the <paramref name="item"/> parameter
/// will still report the last index the item had before the collection
/// was changed.
/// </remarks>
/// <param name="item">
/// The listview item to lookup. If you have
/// associated an object with the Tag property it will be available
/// so you can look it up in your own collection.
/// </param>
/// <returns>The new index where this listview item is located.</returns>
protected virtual int IndexOf(ListViewItem item)
{
int result = item.Index;
return result;
}
#endregion
#region Private Methods
private void SetCapacity()
{
if (this.capacity > 0 && this.IsHandleCreated)
{
const int LVM_SETITEMCOUNT = LvmFirst + 47;
const int LVSICF_NOINVALIDATEALL = 1;
NativeMethods.SendMessage(this, LVM_SETITEMCOUNT, this.capacity, LVSICF_NOINVALIDATEALL);
}
}
private bool IsPointInCheck(Point point, int index)
{
bool result = false;
if (this.Columns.Count > 0)
{
ListViewItem item = this.Items[index];
int scrollPos = NativeMethods.GetScrollPos(this, true);
int posX = point.X + scrollPos;
const int DefaultStateImageWidth = 16;
int imageWidth = this.StateImageList != null ? this.StateImageList.ImageSize.Width : DefaultStateImageWidth;
int checkStart = imageWidth * item.IndentCount;
int checkStop = checkStart + imageWidth;
result = posX >= checkStart && posX <= checkStop;
}
return result;
}
private void BeginSorterUpdate()
{
if (this.sorterUpdateLevel == 0)
{
this.previousSorter = this.ListViewItemSorter;
this.ListViewItemSorter = null;
}
this.sorterUpdateLevel++;
}
private void EndSorterUpdate()
{
this.sorterUpdateLevel--;
if (this.sorterUpdateLevel == 0)
{
this.ListViewItemSorter = this.previousSorter;
this.previousSorter = null;
}
}
private void GetAsText(string separator, bool includeHeaders, IEnumerable items, TextWriter writer)
{
// Write out the column headers first.
if (includeHeaders)
{
int numColumns = this.Columns.Count;
for (int i = 0; i < numColumns; i++)
{
if (i != 0)
{
writer.Write(separator);
}
writer.Write(this.Columns[i].Text);
}
writer.WriteLine();
}
// Write out the column data.
foreach (ListViewItem item in items)
{
int numSubItems = item.SubItems.Count;
for (int i = 0; i < numSubItems; i++)
{
if (i != 0)
{
writer.Write(separator);
}
writer.Write(item.SubItems[i].Text);
}
writer.WriteLine();
}
}
#endregion
#region Private Types
private sealed class HeaderData
{
#region Constructors
public HeaderData(string name)
{
this.Name = name;
}
#endregion
#region Public Properties
public string Name { get; set; }
public int AutoHeaderWidth { get; set; }
public bool IsLastColumn { get; set; }
#endregion
}
private sealed class Sorter : IComparer
{
#region Private Data Members
private readonly ExtendedListView listView;
private int column = -1;