-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMainForm.EventHandlers.cs
1409 lines (1189 loc) · 58.4 KB
/
MainForm.EventHandlers.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
using EditClipboardContents;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using Windows.UI.Xaml.Documents;
using static EditClipboardContents.ClipboardFormats;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
// Disable IDE warnings that showed up after going from C# 7 to C# 9
#pragma warning disable IDE0079 // Disable message about unnecessary suppression
#pragma warning disable IDE1006 // Disable messages about capitalization of control names
#pragma warning disable IDE0063 // Disable messages about Using expression simplification
#pragma warning disable IDE0090 // Disable messages about New expression simplification
#pragma warning disable IDE0028,IDE0300,IDE0305 // Disable message about collection initialization
#pragma warning disable IDE0074 // Disable message about compound assignment for checking if null
#pragma warning disable IDE0066 // Disable message about switch case expression
#pragma warning disable IDE0017
// Nullable reference types
#nullable enable
namespace EditClipboardContents
{
public partial class MainForm : Form
{
// Utility Variables
private bool suppressTextBoxSelectionChange = false;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
dataGridViewClipboard.MouseWheel += dataGridViewClipboard_MouseWheel;
}
// Form has finished loading and is about to be displayed, but not yet visible
private void MainForm_Load(object sender, EventArgs e)
{
}
// Form is now visible
private void MainForm_Shown(object sender, EventArgs e)
{
// Use BeginInvoke to ensure the form is fully rendered
// Don't put anything outside of BeginInvoke that requires the form to be fully rendered, it will actually run first
this.BeginInvoke(new Action(() =>
{
//ShowLoadingIndicator(true);
RefreshClipboardItems();
//ShowLoadingIndicator(false);
//UpdateSplitterPosition_FitDataGrid(); // Occurs in RefreshClipboardItems
}));
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
}
private void MainForm_Resize(object sender, EventArgs e)
{
if (isResizing) return; // Prevent re-entry
isResizing = true;
splitContainerMain.SuspendLayout();
try
{
// Your existing code...
WhichPanelResize splitAnchor;
int maxSize = (int)Math.Round((decimal)splitContainerMain.Height * (decimal)0.6);
DataGridView dgv = dataGridViewClipboard;
int cellsTotalHeight = dgv.Rows.GetRowsHeight(DataGridViewElementStates.Visible);// + dgv.ColumnHeadersHeight + dgv.Rows.GetRowCount(DataGridViewElementStates.Visible);
if ((dataGridViewClipboard.DisplayedRowCount(includePartialRow: false)) >= dataGridViewClipboard.Rows.Count && cellsTotalHeight <= maxSize)
{
splitAnchor = WhichPanelResize.Bottom;
}
else
{
splitAnchor = WhichPanelResize.Top;
}
if (this.WindowState != FormWindowState.Minimized)
{
UpdateToolLocations(splitAnchor: splitAnchor);
}
previousWindowHeight = this.Height;
previousSplitterDistance = splitContainerMain.SplitterDistance;
}
finally
{
isResizing = false;
splitContainerMain.ResumeLayout();
}
}
private void dataGridViewClipboard_MouseWheel(object sender, MouseEventArgs e)
{
if (((HandledMouseEventArgs)e).Handled == true)
{
return;
}
// Determine direction: -1 for up, 1 for down
int direction = e.Delta > 0 ? -1 : 1;
// Get current selected row index
int currentIndex = dataGridViewClipboard.CurrentCell?.RowIndex ?? -1;
if (currentIndex != -1)
{
// Calculate new index
int newIndex = currentIndex + direction;
// Ensure new index is within bounds
int rowCount = dataGridViewClipboard.Rows.Count;
if (newIndex < 0)
{
newIndex = 0;
}
else if (newIndex >= rowCount)
{
newIndex = rowCount - 1;
}
// If the index has changed, update selection
if (newIndex != currentIndex)
{
SelectRowByRowIndex(newIndex);
}
}
// Mark as handled because the event might get fired multiple times per scroll
((HandledMouseEventArgs)e).Handled = true;
}
private void SelectRowByRowIndex(int newIndex, int focusedCellIndex = -1)
{
if (newIndex >= dataGridViewClipboard.Rows.Count)
{
return;
}
// Use the currently focused cell index if none is provided, or default to zero if there is no focused cell
if (focusedCellIndex == -1)
{
focusedCellIndex = dataGridViewClipboard.CurrentCell?.ColumnIndex ?? 0;
}
dataGridViewClipboard.ClearSelectionNoEvent();
dataGridViewClipboard.Rows[newIndex].Selected = true;
dataGridViewClipboard.CurrentCell = dataGridViewClipboard.Rows[newIndex].Cells[focusedCellIndex];
// Scroll to the new index, but only if it's not already visible
if (newIndex < dataGridViewClipboard.FirstDisplayedScrollingRowIndex
|| newIndex >= dataGridViewClipboard.FirstDisplayedScrollingRowIndex + dataGridViewClipboard.DisplayedRowCount(false))
{
dataGridViewClipboard.FirstDisplayedScrollingRowIndex = newIndex;
}
// No need to call ChangeCellFocusAndDisplayCorrespondingData here because it's called in the selection changed event
}
private void menuHelp_About_Click(object sender, EventArgs e)
{
// Show message box
MessageBox.Show("Edit Clipboard Contents\n\n" +
"Version: " + versionString + "\n\n" +
"Author: ThioJoe" +
" (https://github.com/ThioJoe)",
"About", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void dataGridViewClipboard_KeyDown(object sender, KeyEventArgs e)
{
// If the user presses Ctrl+C, copy the selected rows to the clipboard
if (e.Control && e.KeyCode == Keys.C)
{
e.Handled = true; // Prevents the default copy operation
copyTableRows(copyAllRows: null, noError:true); // Null means entire table will be copied if no rows are selected, otherwise just selected rows
}
}
private void contextMenu_copyRowData_Click(object sender, EventArgs e)
{
copyTableRows(copyAllRows: false);
}
private void contextMenu_copyCell_Click(object sender, EventArgs e)
{
// Get the contents of the selected cell
string cellContents = dataGridViewClipboard.CurrentCell.Value.ToString();
// Copy the cell contents to the clipboard
Utils.CopyIfValid(cellContents, useTooltip: true, relativeForm: this);
}
private void contextMenu_copySelectedRowsNoHeader_Click(object sender, EventArgs e)
{
copyTableRows(copyAllRows: false, forceNoHeader: true);
}
// Used for Right Click Context Menu
private void dataGridViewClipboard_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
void headerOptionsVisibility(bool visible)
{
contextMenu_copyColumn.Visible = visible;
contextMenu_copyColumnNoHeader.Visible = visible;
}
void cellOptionsVisibility(bool visible)
{
contextMenu_copySingleCell.Visible = visible;
contextMenu_copySelectedCurrentColumnOnly.Visible = visible;
contextMenu_copySelectedRows.Visible = visible;
contextMenu_copySelectedRowsNoHeader.Visible = visible;
}
// -----------------------------------------------------------------------------------
if (recentRightClickedCell == null)
{
recentRightClickedCell = new RecentRightClickedCell();
}
if (e.Button == MouseButtons.Right)
{
// Note cell row and column that was right clicked
recentRightClickedCell.RowIndex = e.RowIndex;
recentRightClickedCell.ColumnIndex = e.ColumnIndex;
// Check if the clicked row is part of the current selection
bool isClickedRowSelected = false;
foreach (DataGridViewRow row in dataGridViewClipboard.SelectedRows)
{
if (row.Index == e.RowIndex)
{
isClickedRowSelected = true;
break;
}
}
// If right click target is a header, show specific options
if (e.RowIndex == -1)
{
headerOptionsVisibility(visible: true);
cellOptionsVisibility(visible: false);
}
else
{
// Baseline visibility, adjust specifics next
headerOptionsVisibility(visible: false);
cellOptionsVisibility(visible: true);
// If more than one row is selected, hide the "Copy Single Cell" option and display the Copy Column button, and vice versa
if (dataGridViewClipboard.SelectedRows.Count > 1)
{
contextMenu_copySingleCell.Visible = false;
contextMenu_copySelectedCurrentColumnOnly.Visible = true;
}
else
{
contextMenu_copySingleCell.Visible = true;
contextMenu_copySelectedCurrentColumnOnly.Visible = false;
}
// If the clicked row is not part of the current selection, clear the selection and re-set the clicked row as the only selected row
if (!isClickedRowSelected)
{
dataGridViewClipboard.ClearSelectionNoEvent();
dataGridViewClipboard.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
// Change the cell focus
ChangeCellFocusAndDisplayCorrespondingData(rowIndex: e.RowIndex, cellIndex: e.ColumnIndex);
}
// If only one row is selected, change the cell focus
else if (isClickedRowSelected && dataGridViewClipboard.SelectedRows.Count == 1)
{
ChangeCellFocusAndDisplayCorrespondingData(rowIndex: e.RowIndex, cellIndex: e.ColumnIndex);
}
}
}
}
private void contextMenu_copyColumn_Click(object sender, EventArgs e)
{
int columnIndex = recentRightClickedCell?.ColumnIndex ?? -1;
copyTableRows(copyAllRows: true, forceNoHeader: false, onlyColumnIndex: columnIndex);
}
private void contextMenu_copyColumnNoHeader_Click(object sender, EventArgs e)
{
int columnIndex = recentRightClickedCell?.ColumnIndex ?? -1;
copyTableRows(copyAllRows: true, forceNoHeader: true, onlyColumnIndex: columnIndex);
}
private void contextMenu_copySelectedCurrentColumnOnly_Click(object sender, EventArgs e)
{
int columnIndex = recentRightClickedCell?.ColumnIndex ?? -1;
copyTableRows(copyAllRows: false, forceNoHeader: true, onlyColumnIndex: columnIndex);
}
private void contextMenuStrip_dataGridView_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
}
private void menuOptions_IncludeRowHeaders_Click(object sender, EventArgs e)
{
// Toggle the check based on the current state
menuOptions_IncludeRowHeaders.Checked = !menuOptions_IncludeRowHeaders.Checked;
}
// ---------------------- Table Copy Formatting Options ----------------------
private void menuOptions_TabSeparation_Click(object sender, EventArgs e)
{
// Use pattern matchin to get the text of the clicked item and pass it in to the function automatically
if (sender is MenuItem clickedItem)
{
setCopyModeChecks(clickedItem);
}
}
private void menuOptions_CommaSeparation_Click(object sender, EventArgs e)
{
if (sender is MenuItem clickedItem)
{
setCopyModeChecks(clickedItem);
}
}
private void menuOptions_PreFormatted_Click(object sender, EventArgs e)
{
if (sender is MenuItem clickedItem)
{
setCopyModeChecks(clickedItem);
}
}
private void menuItemShowLargeHex_Click(object sender, EventArgs e)
{
// Toggle the check based on the current state
menuOptions_ShowLargeHex.Checked = !menuOptions_ShowLargeHex.Checked;
}
// Give focus to control when mouse enters. I don't remember why I did this
private void dataGridViewClipboard_MouseEnter(object sender, EventArgs e)
{
// Ensure the parent window has focus before giving focus to the control, so the control doesn't steal focus from other windows
if ( this.ContainsFocus ) // "this" refers to the window
{
dataGridViewClipboard.Focus();
}
}
private void buttonResetEdit_Click(object sender, EventArgs e)
{
Guid guid;
byte[]? originalData;
ClipboardItem? originalItem = GetSelectedClipboardItemObject(returnEditedItemVersion: false);
if (originalItem != null)
{
originalData = originalItem.RawData;
}
else // It must be a custom format so there is no original data. Assume user wants to reset the custom format data and removal status
{
originalItem = GetSelectedClipboardItemObject(returnEditedItemVersion: true);
originalData = new byte[0];
}
if (originalItem == null)
{
return; // Something else went wrong, just return
}
guid = originalItem.UniqueID;
// Get the original item's data and apply it to the edited item
UpdateEditedClipboardItemRawData(guid, originalData, setPendingEdit: false, setPendingRemoval: false);
ResetOrderIndexes();
// Check if any edited items still have pending changes or are pending removal, and update the pending changes label if necessary
UpdateAnyPendingChangesFlag();
// Update the view. Edited version should be the same as the original version now
DisplayClipboardDataInTextBoxes(GetSelectedClipboardItemObject(returnEditedItemVersion: true));
UpdateEditControlsVisibility_AndPendingGridAppearance();
}
private void dataGridViewClipboard_SelectionChanged(object sender, EventArgs e)
{
void buttonStatus_RequireSelection(bool enabledChoice, bool onlyCustomIncompatible = false)
{
// Custom incompatible
menuEdit_CopySelectedRows.Enabled = enabledChoice;
menuFile_ExportSelectedAsRawHex.Enabled = enabledChoice;
menuFile_ExportSelectedStruct.Enabled = enabledChoice;
menuFile_ExportSelectedAsFile.Enabled = enabledChoice;
if (!onlyCustomIncompatible)
{
// Able to be used with custom formats
menuTools_LoadBinaryDataToSelected.Enabled = enabledChoice;
}
}
// -------------------------------------------------------------
if (dataGridViewClipboard.SelectedRows.Count == 0)
{
richTextBoxContents.Text = "";
// Disable menu buttons that require a selectedItem
buttonStatus_RequireSelection(enabledChoice: false);
return;
}
// Assume focus of the first selected row if multiple are selected
ChangeCellFocusAndDisplayCorrespondingData(dataGridViewClipboard.SelectedRows[0].Index);
// If it's a custom format, disable the buttons and always go to the edit view
if (GetSelectedDataFromDataGridView(colName.FormatType) == FormatTypeNames.Custom)
{
buttonStatus_RequireSelection(enabledChoice: false, onlyCustomIncompatible: true);
dropdownContentsViewMode.SelectedIndex = (int)ViewMode.HexEdit; // Hex (Editable)
checkBoxPlainTextEditing.Checked = true;
return;
}
// Enable menu buttons that require a selectedItem
buttonStatus_RequireSelection(enabledChoice: true);
// If the auto selection checkbox is checked, decide which view mode to use based on item data
if (checkBoxAutoViewMode.Checked)
{
// Get the selectedItem object
ClipboardItem? item = GetSelectedClipboardItemObject(returnEditedItemVersion: true);
if (item == null)
{
return; // If the item is null, just return
}
// If a preferred view mode is set, prioritize that
if (item.PreferredViewMode != ViewMode.None)
{
dropdownContentsViewMode.SelectedIndex = (int)item.PreferredViewMode;
return;
}
// If there is a text preview, show text mode
if (!string.IsNullOrEmpty(GetSelectedDataFromDataGridView(colName.TextPreview)))
{
dropdownContentsViewMode.SelectedIndex = (int)ViewMode.Text; // Text
}
// If there is data object info, show object view mode. Also show if there are multiple data info entries or the first one isn't empty
else if (item != null && (
item.ClipDataObject != null
|| (item.RawData != null && item.RawData.Length > 5000) // If data is enough to cause performance issues in hex view, show object view
|| (item.DataInfoList != null
&& (item.DataInfoList.Count > 1
|| (item.DataInfoList.Count > 0 && !string.IsNullOrEmpty(item.DataInfoList[0]))
)
)
))
{
dropdownContentsViewMode.SelectedIndex = (int)ViewMode.Object; // Object View
}
else
{
dropdownContentsViewMode.SelectedIndex = (int)ViewMode.Hex; // Hex View (Non Editable)
}
}
}
private void menuEdit_CopyHexAsText_Click(object sender, EventArgs e)
{
// Get the clipboard selectedItem and its info
ClipboardItem? itemToCopy = GetSelectedClipboardItemObject(returnEditedItemVersion: false);
if (itemToCopy == null)
{
return;
}
// Get the hex information that would be displayed in the hex view
string data = BitConverter.ToString(itemToCopy.RawData).Replace("-", " ");
// Copy the hex information to the clipboard
Utils.CopyIfValid(data, useTooltip: false);
}
private void menuEdit_CopyObjectInfoAsText_Click(object sender, EventArgs e)
{
// Get the clipboard selectedItem and its info
ClipboardItem? itemToCopy = GetSelectedClipboardItemObject(returnEditedItemVersion: false);
if (itemToCopy == null)
{
return;
}
// Get the struct / object info that would be displayed in object view of rich text box and copy it to clipboard
string data = FormatStructurePrinter.GetDataStringForTextbox(formatName: Utils.GetClipboardFormatNameFromId(itemToCopy.FormatId), fullItem: itemToCopy, plaintext:true);
Utils.CopyIfValid(data, useTooltip: false);
}
private void menuEdit_CopyEditedHexAsText_Click(object sender, EventArgs e)
{
// Get the edited clipboard selectedItem and its info
ClipboardItem? itemToCopy = GetSelectedClipboardItemObject(returnEditedItemVersion: true);
if (itemToCopy == null)
{
return;
}
// Get the hex information that would be displayed in the hex view and copy it to clipboard
string data = BitConverter.ToString(itemToCopy.RawData).Replace("-", " ");
Utils.CopyIfValid(data, useTooltip: false);
}
private void menuEdit_CopySelectedRows_Click(object sender, EventArgs e)
{
// If no rows are selected, do nothing
if (dataGridViewClipboard.SelectedRows.Count == 0)
{
return;
}
copyTableRows(copyAllRows: false);
}
private void menuEdit_CopyEntireTable_Click(object sender, EventArgs e)
{
copyTableRows(copyAllRows: true);
}
// Converts the hex string in the hex view to a byte array and updates the clipboard selectedItem in editedClipboardItems
private void buttonApplyEdit_Click(object sender, EventArgs e)
{
// Get the hex string from the hex view
string hexString = Regex.Replace(richTextBoxContents.Text, @"\s", "");
// Ensure valid number of characters and the text is valid Hex
if (hexString.Length % 2 != 0)
{
MessageBox.Show($"Invalid hex data. There must be an even number of hex characters (spaces and whitespace are ignored).\n\nInput length was: {hexString.Length}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Check for invalid characters
Match invalidMatch = Regex.Match(hexString, @"[^0-9a-fA-F]");
if (invalidMatch.Success)
{
string invalidChars = string.Join(", ", hexString.Where(c => !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))).Distinct());
MessageBox.Show($"Invalid hex data. Please ensure the text box only contains valid hex characters (0-9, A-F).\n\nInvalid characters found: {invalidChars}\n\n(Spaces and whitespace are automatically ignored)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
byte[] rawDataFromTextbox = Enumerable.Range(0, hexString.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
.ToArray();
// Get the format ID of the selected clipboard selectedItem
Guid uniqueID = GetSelectedClipboardItemObject(returnEditedItemVersion: true)?.UniqueID ?? Guid.Empty;
if (uniqueID == Guid.Empty)
{
return;
}
ClipboardItem? originalItem = GetSelectedClipboardItemObject(returnEditedItemVersion: false);
// Check if the edited data is actually different from the original data, apply the change and set anyPendingChanges accordingly
// First check if there is even an original item. If not it's probably a custom added item so just updated it
if (originalItem == null)
{
UpdateEditedClipboardItemRawData(uniqueID, rawDataFromTextbox);
anyPendingChanges = true;
}
else if(!originalItem.RawData.SequenceEqual(rawDataFromTextbox))
{
UpdateEditedClipboardItemRawData(uniqueID, rawDataFromTextbox);
anyPendingChanges = true;
}
else
{
// Don't change anyPendingChanges to false because there might be other items with pending changes
}
UpdateEditControlsVisibility_AndPendingGridAppearance();
}
private void toolStripButtonSaveEdited_Click(object sender, EventArgs e)
{
// Trigger the end edit event to save the current cell
dataGridViewClipboard.EndEdit();
if (!ValidateCustomFormats())
{
return;
}
SaveClipboardData();
//anyPendingChanges = false; // Moved into RefreshClipboardItems
RefreshClipboardItems();
//UpdateEditControlsVisibility_AndPendingGridAppearance(); // Occurs in RefreshClipboardItems
}
private void menuFile_ExportSelectedAsRawHex_Click(object sender, EventArgs e)
{
ClipboardItem? itemToExport = GetSelectedClipboardItemObject(returnEditedItemVersion: false);
if (itemToExport == null)
{
return;
}
string nameStem = itemToExport.FormatName + "_RawHex";
SaveFileDialog saveFileDialogResult = SaveFileDialog(extension: "txt", defaultFileNameStem: nameStem);
if (saveFileDialogResult.ShowDialog() == DialogResult.OK)
{
// Get the hex information
string data = BitConverter.ToString(itemToExport.RawData).Replace("-", " ");
// Save the data to a file
File.WriteAllText(saveFileDialogResult.FileName, data);
}
}
private void menuFile_ExportSelectedStruct_Click(object sender, EventArgs e)
{
// Get the clipboard selectedItem and its info
ClipboardItem? itemToExport = GetSelectedClipboardItemObject(returnEditedItemVersion: false);
if (itemToExport == null)
{
return;
}
string nameStem = itemToExport.FormatName + "_StructInfo";
SaveFileDialog saveFileDialogResult = SaveFileDialog(extension: "txt", defaultFileNameStem: nameStem);
if (saveFileDialogResult.ShowDialog() == DialogResult.OK)
{
// Get the hex information
string data = FormatStructurePrinter.GetDataStringForTextbox(formatName: Utils.GetClipboardFormatNameFromId(itemToExport.FormatId), fullItem: itemToExport, plaintext:true);
// TO DO - Export details of each object in the struct
// Save the data to a file
File.WriteAllText(saveFileDialogResult.FileName, data);
}
}
private void menuFile_ExportSelectedAsFile_Click(object sender, EventArgs e)
{
List<ClipboardItem>? selectedItems = GetSelectedClipboardItemObjectList(returnEditedItemVersion: false);
if (selectedItems == null || selectedItems.Count == 0)
{
return;
}
foreach (ClipboardItem item in selectedItems)
{
SaveBinaryFile(item);
}
}
private void toolStripButtonExportSelected_Click(object sender, EventArgs e)
{
List<ClipboardItem>? selectedItems = GetSelectedClipboardItemObjectList(returnEditedItemVersion: false);
if (selectedItems == null || selectedItems.Count == 0)
{
return;
}
foreach (ClipboardItem item in selectedItems)
{
SaveBinaryFile(item);
}
}
private void toolStripButtonRefresh_Click(object sender, EventArgs e)
{
RefreshClipboardAndRestoreSelection();
}
private void toolStripButtonTimedRefresh_Click(object sender, EventArgs e)
{
// Get input from the user from a message box. The user should input a number of seconds
string input = "";
DialogResult inputResult = Utils.ShowInputDialog(owner: this, ref input, instructions: "Enter a delay in seconds before refreshing:"); // Will put the user input in the "input" variable
if (inputResult == DialogResult.Cancel)
{
return;
}
if (uint.TryParse(input, out uint delay))
{
// Create the timer
Timer refreshTimer = new Timer();
refreshTimer.Interval = (int)delay * 1000; // Convert seconds to milliseconds
refreshTimer.Tick += (object sender, EventArgs e) =>
{
RefreshClipboardAndRestoreSelection();
refreshTimer.Stop();
refreshTimer.Dispose();
};
// Actually run the timer and code inside the tick event
refreshTimer.Start();
}
else
{
MessageBox.Show("Invalid input. Please enter a valid number of seconds.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void toolStripButtonDelete_Click(object sender, EventArgs e)
{
if (dataGridViewClipboard.SelectedRows.Count > 0)
{
foreach (DataGridViewRow selectedRow in dataGridViewClipboard.SelectedRows)
{
if (Guid.TryParse(selectedRow.Cells[colName.UniqueID].Value.ToString(), out Guid uniqueID))
{
// Update editedClipboardItems to mark the item as deleted
MarkIndividualClipboardItemForRemoval(uniqueID);
}
}
UpdateEditControlsVisibility_AndPendingGridAppearance();
}
}
private void splitContainerMain_SplitterMoved(object sender, SplitterEventArgs e)
{
// Resize processedData grid view to fit the form window
UpdateToolLocations();
}
// If double click on the splitter bar, fit the datagridview to the available space (resets the splitter position to fit data grid)
private void splitContainerMain_DoubleClick(object sender, EventArgs e)
{
SplitContainer container = (SplitContainer)sender;
Point clickPoint = container.PointToClient(Cursor.Position);
// Define the area of the splitter
Rectangle splitterRect;
if (container.Orientation == Orientation.Vertical)
{
splitterRect = new Rectangle(container.SplitterDistance, 0, container.SplitterWidth, container.Height);
}
else
{
splitterRect = new Rectangle(0, container.SplitterDistance, container.Width, container.SplitterWidth);
}
if (splitterRect.Contains(clickPoint))
{
UpdateSplitterPosition_FitDataGrid(force: true);
}
}
private void dropdownContentsViewMode_SelectedIndexChanged(object sender, EventArgs e)
{
// Indexes:
// 0: Text
// 1: Hex
// 2: Hex (Editable)
// 3: Object / Struct View
// Show buttons and labels for edited mode
UpdateEditControlsVisibility_AndPendingGridAppearance();
// For object view mode and text view mode, enable auto highlighting URLs in the text box
if (dropdownContentsViewMode.SelectedIndex == (int)ViewMode.Text || dropdownContentsViewMode.SelectedIndex == (int)ViewMode.Object)
{
richTextBoxContents.DetectUrls = true;
}
else
{
richTextBoxContents.DetectUrls = false;
}
ClipboardItem? item = GetSelectedClipboardItemObject(returnEditedItemVersion: true);
if (item == null)
{
return;
}
DisplayClipboardDataInTextBoxes(item);
}
// Left Click
private void dataGridViewClipboard_CellClick(object sender, DataGridViewCellEventArgs e)
{
ChangeCellFocusAndDisplayCorrespondingData(e.RowIndex);
UpdateEditControlsVisibility_AndPendingGridAppearance();
}
private void dataGridViewClipboard_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
// If it's the format ID column or another numerical column, sort them numerically instead of alphabetically
if (e.Column.Name == colName.FormatId || e.Column.Name == colName.Index)
{
// Try to parse the values as numbers
if (int.TryParse(e.CellValue1?.ToString(), out int value1) &&
int.TryParse(e.CellValue2?.ToString(), out int value2))
{
// Compare the parsed numeric values
e.SortResult = value1.CompareTo(value2);
e.Handled = true;
}
}
}
private void dataGridViewClipboard_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == dataGridViewClipboard.Columns[colName.Index].Index)
{
// Suspend layout updates
dataGridViewClipboard.SuspendLayout();
// Sort the Index column
dataGridViewClipboard.Sort(dataGridViewClipboard.Columns[colName.Index], System.ComponentModel.ListSortDirection.Ascending);
// Hide the sort indicator
dataGridViewClipboard.Columns[colName.Index].HeaderCell.SortGlyphDirection = SortOrder.None;
// Resume layout updates
dataGridViewClipboard.ResumeLayout();
}
else
{
// Set the focused cell to the same column as the clicked header
dataGridViewClipboard.CurrentCell = dataGridViewClipboard.Rows[0].Cells[e.ColumnIndex];
}
}
private void menuHelp_WhyTakingLong_Click(object sender, EventArgs e)
{
MessageBox.Show("In some cases, loading the clipboard may take longer than expected.\n\n" +
"The reason is that many apps use a clipboard feature called \"Delayed Rendering\" to " +
"optimize performance. With delayed rendering, apps don't actually copy data to the " +
"clipboard until another app requests it.\n\n" +
"When this app fetches the clipboard, it requests ALL of these delayed render formats for " +
"so you can view the contents, causing the original apps to generate and transfer the data on demand. " +
"This process can take time, especially for large amounts of data or complex formats.\n\n" +
"This is also why you usually never notice the delay when pasting data into another app.",
"Why is clipboard loading slow?", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void toolStripButtonAddFormat_Click(object sender, EventArgs e)
{
int itemIndex = dataGridViewClipboard.Rows.Count; // The index of the current last item will be (count - 1) so the new item will be at index count
string customName = MyStrings.DefaultCustomFormatName;
// Check if the default name is already in use. If so, add a number to the end
if (editedClipboardItems.Any(item => item.FormatName == customName))
{
int i = 1;
while (editedClipboardItems.Any(item => item.FormatName == customName + " " + i))
{
i++;
}
customName = $"{customName} {i}";
}
// Create a new boilerplate clipboard item
ClipboardItem? newItem = new ClipboardItem()
{
FormatId = 0,
FormatName = customName,
RawData = new byte[0],
ClipDataObject = null,
DataInfoList = [ MyStrings.CustomPendingData ],
OriginalIndex = itemIndex,
FormatType = FormatTypeNames.Custom,
PendingCustomAddition = true,
};
//UpdateClipboardItemsGridView_WithEmptyCustomFormat(newItem);
editedClipboardItems.Add(newItem);
anyPendingChanges = true;
RefreshDataGridViewContents();
UpdateSplitterPosition_FitDataGrid();
//UpdateEditControlsVisibility_AndPendingGridAppearance(); // Occurs in RefreshDataGridViewContents
// Set selected rows to just the new row
dataGridViewClipboard.ClearSelectionNoEvent();
dataGridViewClipboard.Rows[itemIndex].Selected = true;
// if the row isn't visible, scroll to it
if (itemIndex >= dataGridViewClipboard.FirstDisplayedScrollingRowIndex + dataGridViewClipboard.DisplayedRowCount(false))
{
dataGridViewClipboard.FirstDisplayedScrollingRowIndex = itemIndex;
}
}
private void dataGridViewClipboard_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
// Ensure the indexes are valid
if (e.RowIndex < 0 || e.ColumnIndex < 0)
{
return;
}
// Reset editability of the grid to false by default
dataGridViewClipboard.ReadOnly = true;
dataGridViewClipboard[e.ColumnIndex, e.RowIndex].ReadOnly = false;
// Only allow editing for custom added formats
ClipboardItem? item = GetSelectedClipboardItemObject(returnEditedItemVersion: true);
if (item != null && item.PendingCustomAddition == true)
{
int rowIndex = e.RowIndex;
int columnIndex = e.ColumnIndex;
string columnName = dataGridViewClipboard.Columns[columnIndex].Name;
List<string> allowedToEditColumns = new List<string> { colName.FormatName, colName.FormatId };
// Dictionary with reasons not allowed to edit specific columns
Dictionary<string, string> notAllowedToEditColumns = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
//{ colName.FormatId, "Cannot Edit Format ID: This number is set automatically by windows." },
{ colName.FormatType, "Cannot Edit Format Type: This column is informational only derived from other properties, it is not an actual value." },
{ colName.Index, "Index cannot currently be changed." },
};
if (allowedToEditColumns.Contains(columnName))
{
dataGridViewClipboard.ReadOnly = false;
dataGridViewClipboard[columnIndex, rowIndex].ReadOnly = false;
dataGridViewClipboard.BeginEdit(true);
}
else
{
// If a message is available for the column, show it.
if (notAllowedToEditColumns.TryGetValue(columnName, out string message))
{
MessageBox.Show(message, "Cannot Edit Column", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
private void dataGridViewClipboard_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
itemBeforeCellEditClone = null;
itemBeforeCellEditClone = (ClipboardItem?)GetSelectedClipboardItemObject(returnEditedItemVersion: true)?.Clone();
}
private void dataGridViewClipboard_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// Get the item before the cell was edited
ClipboardItem? itemBeforeEdit = itemBeforeCellEditClone;
if (itemBeforeEdit == null)
{
MessageBox.Show("Error: Couldn't find the clipboard object from before the edit.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DataGridViewRow row = dataGridViewClipboard.Rows[e.RowIndex];
// If the edited cell is in the name column, set the value in the format id column to 0
if (dataGridViewClipboard.Columns[e.ColumnIndex].Name == colName.FormatName)
{
// Currently no cell value change event handler so no need to disable it, otherwise we would
row.Cells[colName.FormatId].Value = MyStrings.DefaultCustomFormatID;
}
// If the edited cell is in the format id column, set the value in the format name column to say custom format
else if (dataGridViewClipboard.Columns[e.ColumnIndex].Name == colName.FormatId)
{
row.Cells[colName.FormatName].Value = MyStrings.DefaultCustomFormatName;
}
// Updates the editedClipboardItems list with the new data
Guid uniqueID = itemBeforeEdit.UniqueID;
uint formatId = uint.Parse(row.Cells[colName.FormatId].Value.ToString());
string formatName = row.Cells[colName.FormatName].Value.ToString();
// Will need to add a validation function here later
// Update the edited item
ClipboardItem? editedItem = editedClipboardItems.FirstOrDefault(i => i.UniqueID == uniqueID);
if (editedItem != null)
{