-
Notifications
You must be signed in to change notification settings - Fork 71
/
TitleBarTabsOverlay.cs
1172 lines (987 loc) · 39.8 KB
/
TitleBarTabsOverlay.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 System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Win32Interop.Enums;
using Win32Interop.Methods;
using Win32Interop.Structs;
using Timer = System.Timers.Timer;
namespace EasyTabs
{
/// <summary>
/// Borderless overlay window that is moved with and rendered on top of the non-client area of a <see cref="TitleBarTabs" /> instance that's responsible
/// for rendering the actual tab content and responding to click events for those tabs.
/// </summary>
public class TitleBarTabsOverlay : Form
{
protected Timer showTooltipTimer;
/// <summary>All of the parent forms and their overlays so that we don't create duplicate overlays across the application domain.</summary>
protected static Dictionary<TitleBarTabs, TitleBarTabsOverlay> _parents = new Dictionary<TitleBarTabs, TitleBarTabsOverlay>();
/// <summary>Tab that has been torn off from this window and is being dragged.</summary>
protected static TitleBarTab _tornTab;
/// <summary>Thumbnail representation of <see cref="_tornTab" /> used when dragging.</summary>
protected static TornTabForm _tornTabForm;
/// <summary>
/// Flag used in <see cref="WndProc" /> and <see cref="MouseHookCallback" /> to track whether the user was click/dragging when a particular event
/// occurred.
/// </summary>
protected static bool _wasDragging = false;
/// <summary>Flag indicating whether or not <see cref="_hookproc" /> has been installed as a hook.</summary>
protected static bool _hookProcInstalled;
/// <summary>Semaphore to control access to <see cref="_tornTab" />.</summary>
protected static object _tornTabLock = new object();
protected static uint _doubleClickInterval = User32.GetDoubleClickTime();
/// <summary>Flag indicating whether or not the underlying window is active.</summary>
protected bool _active = false;
/// <summary>Flag indicating whether we should draw the titlebar background (i.e. we are in a non-Aero environment).</summary>
protected bool _aeroEnabled = false;
/// <summary>
/// When a tab is torn from the window, this is where we store the areas on all open windows where tabs can be dropped to combine the tab with that
/// window.
/// </summary>
protected Tuple<TitleBarTabs, Rectangle>[] _dropAreas = null;
/// <summary>Pointer to the low-level mouse hook callback (<see cref="MouseHookCallback" />).</summary>
protected IntPtr _hookId;
/// <summary>Delegate of <see cref="MouseHookCallback" />; declared as a member variable to keep it from being garbage collected.</summary>
protected HOOKPROC _hookproc = null;
/// <summary>Index of the tab, if any, whose close button is being hovered over.</summary>
protected int _isOverCloseButtonForTab = -1;
protected bool _isOverSizingBox = false;
protected bool _isOverAddButton = true;
/// <summary>Queue of mouse events reported by <see cref="_hookproc" /> that need to be processed.</summary>
protected BlockingCollection<MouseEvent> _mouseEvents = new BlockingCollection<MouseEvent>();
/// <summary>Consumer thread for processing events in <see cref="_mouseEvents" />.</summary>
protected Thread _mouseEventsThread = null;
/// <summary>Parent form for the overlay.</summary>
protected TitleBarTabs _parentForm;
protected long _lastLeftButtonClickTicks = 0;
protected bool _firstClick = true;
protected Point[] _lastTwoClickCoordinates = new Point[2];
protected bool _parentFormClosing = false;
/// <summary>Blank default constructor to ensure that the overlays are only initialized through <see cref="GetInstance" />.</summary>
protected TitleBarTabsOverlay()
{
}
/// <summary>Creates the overlay window and attaches it to <paramref name="parentForm" />.</summary>
/// <param name="parentForm">Parent form that the overlay should be rendered on top of.</param>
protected TitleBarTabsOverlay(TitleBarTabs parentForm)
{
_parentForm = parentForm;
// We don't want this window visible in the taskbar
ShowInTaskbar = false;
FormBorderStyle = FormBorderStyle.SizableToolWindow;
MinimizeBox = false;
MaximizeBox = false;
_aeroEnabled = _parentForm.IsCompositionEnabled;
Show(_parentForm);
AttachHandlers();
showTooltipTimer = new Timer
{
AutoReset = false
};
showTooltipTimer.Elapsed += ShowTooltipTimer_Elapsed;
}
/// <summary>
/// Makes sure that the window is created with an <see cref="WS_EX.WS_EX_LAYERED" /> flag set so that it can be alpha-blended properly with the content (
/// <see cref="_parentForm" />) underneath the overlay.
/// </summary>
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.ExStyle |= (int) (WS_EX.WS_EX_LAYERED | WS_EX.WS_EX_NOACTIVATE);
return createParams;
}
}
/// <summary>Primary color for the titlebar background.</summary>
protected Color TitleBarColor
{
get
{
if (Application.RenderWithVisualStyles && Environment.OSVersion.Version.Major >= 6)
{
return _active
? SystemColors.GradientActiveCaption
: SystemColors.GradientInactiveCaption;
}
return _active
? SystemColors.ActiveCaption
: SystemColors.InactiveCaption;
}
}
/// <summary>Type of theme being used by the OS to render the desktop.</summary>
protected DisplayType DisplayType
{
get
{
if (_aeroEnabled)
{
return DisplayType.Aero;
}
if (Application.RenderWithVisualStyles && Environment.OSVersion.Version.Major >= 6)
{
return DisplayType.Basic;
}
return DisplayType.Classic;
}
}
/// <summary>Gradient color for the titlebar background.</summary>
protected Color TitleBarGradientColor
{
get
{
return _active
? SystemInformation.IsTitleBarGradientEnabled
? SystemColors.GradientActiveCaption
: SystemColors.ActiveCaption
: SystemInformation.IsTitleBarGradientEnabled
? SystemColors.GradientInactiveCaption
: SystemColors.InactiveCaption;
}
}
/// <summary>Screen area in which tabs can be dragged to and dropped for this window.</summary>
public Rectangle TabDropArea
{
get
{
RECT windowRectangle;
User32.GetWindowRect(_parentForm.Handle, out windowRectangle);
return new Rectangle(
windowRectangle.left + SystemInformation.HorizontalResizeBorderThickness, windowRectangle.top + SystemInformation.VerticalResizeBorderThickness,
ClientRectangle.Width, _parentForm.NonClientAreaHeight - SystemInformation.VerticalResizeBorderThickness);
}
}
/// <summary>Retrieves or creates the overlay for <paramref name="parentForm" />.</summary>
/// <param name="parentForm">Parent form that we are to create the overlay for.</param>
/// <returns>Newly-created or previously existing overlay for <paramref name="parentForm" />.</returns>
public static TitleBarTabsOverlay GetInstance(TitleBarTabs parentForm)
{
if (!_parents.ContainsKey(parentForm))
{
_parents.Add(parentForm, new TitleBarTabsOverlay(parentForm));
}
return _parents[parentForm];
}
/// <summary>
/// Attaches the various event handlers to <see cref="_parentForm" /> so that the overlay is moved in synchronization to
/// <see cref="_parentForm" />.
/// </summary>
protected void AttachHandlers()
{
FormClosing += TitleBarTabsOverlay_FormClosing;
_parentForm.FormClosing += _parentForm_FormClosing;
_parentForm.Disposed += _parentForm_Disposed;
_parentForm.Deactivate += _parentForm_Deactivate;
_parentForm.Activated += _parentForm_Activated;
_parentForm.SizeChanged += _parentForm_Refresh;
_parentForm.Shown += _parentForm_Refresh;
_parentForm.VisibleChanged += _parentForm_Refresh;
_parentForm.Move += _parentForm_Refresh;
_parentForm.SystemColorsChanged += _parentForm_SystemColorsChanged;
if (_hookproc == null)
{
// Spin up a consumer thread to process mouse events from _mouseEvents
_mouseEventsThread = new Thread(InterpretMouseEvents)
{
Name = "Low level mouse hooks processing thread"
};
_mouseEventsThread.Priority = ThreadPriority.Highest;
_mouseEventsThread.Start();
using (Process curProcess = Process.GetCurrentProcess())
{
using (ProcessModule curModule = curProcess.MainModule)
{
// Install the low level mouse hook that will put events into _mouseEvents
_hookproc = MouseHookCallback;
_hookId = User32.SetWindowsHookEx(WH.WH_MOUSE_LL, _hookproc, Kernel32.GetModuleHandle(curModule.ModuleName), 0);
}
}
}
}
private void TitleBarTabsOverlay_FormClosing(object sender, FormClosingEventArgs e)
{
if (!_parentFormClosing)
{
e.Cancel = true;
_parentFormClosing = true;
_parentForm.Close();
}
}
/// <summary>
/// Event handler that is called when <see cref="_parentForm" /> is in the process of closing. This uninstalls <see cref="_hookproc" /> from the low-
/// level hooks list and stops the consumer thread that processes those events.
/// </summary>
/// <param name="sender">Object from which this event originated, <see cref="_parentForm" /> in this case.</param>
/// <param name="e">Arguments associated with this event.</param>
private void _parentForm_FormClosing(object sender, CancelEventArgs e)
{
if (e.Cancel)
{
_parentFormClosing = false;
return;
}
TitleBarTabs form = (TitleBarTabs) sender;
if (form == null)
{
return;
}
_parentFormClosing = true;
if (_parents.ContainsKey(form))
{
_parents.Remove(form);
}
// Uninstall the mouse hook
User32.UnhookWindowsHookEx(_hookId);
// Kill the mouse events processing thread
_mouseEvents.CompleteAdding();
_mouseEventsThread.Abort();
}
private void HideTooltip()
{
showTooltipTimer.Stop();
if (_parentForm.InvokeRequired)
{
_parentForm.Invoke(new Action(() =>
{
_parentForm.Tooltip.Hide(_parentForm);
}));
}
else
{
_parentForm.Tooltip.Hide(_parentForm);
}
}
private void ShowTooltip(TitleBarTabs tabsForm, string caption)
{
Point tooltipLocation = new Point(Cursor.Position.X + 7, Cursor.Position.Y + 55);
tabsForm.Tooltip.Show(caption, tabsForm, tabsForm.PointToClient(tooltipLocation), tabsForm.Tooltip.AutoPopDelay);
}
private void ShowTooltipTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (!_parentForm.ShowTooltips)
{
return;
}
Point relativeCursorPosition = GetRelativeCursorPosition(Cursor.Position);
TitleBarTab hoverTab = _parentForm.TabRenderer.OverTab(_parentForm.Tabs, relativeCursorPosition);
if (hoverTab != null)
{
TitleBarTabs hoverTabForm = hoverTab.Parent;
if (hoverTabForm.InvokeRequired)
{
hoverTabForm.Invoke(new Action(() =>
{
ShowTooltip(hoverTabForm, hoverTab.Caption);
}));
}
else
{
ShowTooltip(hoverTabForm, hoverTab.Caption);
}
}
}
private void StartTooltipTimer()
{
if (!_parentForm.ShowTooltips)
{
return;
}
Point relativeCursorPosition = GetRelativeCursorPosition(Cursor.Position);
TitleBarTab hoverTab = _parentForm.TabRenderer.OverTab(_parentForm.Tabs, relativeCursorPosition);
if (hoverTab != null)
{
showTooltipTimer.Interval = hoverTab.Parent.Tooltip.AutomaticDelay;
showTooltipTimer.Start();
}
}
/// <summary>Consumer method that processes mouse events in <see cref="_mouseEvents" /> that are recorded by <see cref="MouseHookCallback" />.</summary>
protected void InterpretMouseEvents()
{
foreach (MouseEvent mouseEvent in _mouseEvents.GetConsumingEnumerable())
{
int nCode = mouseEvent.nCode;
IntPtr wParam = mouseEvent.wParam;
MSLLHOOKSTRUCT? hookStruct = mouseEvent.MouseData;
if (nCode >= 0 && (int) WM.WM_MOUSEMOVE == (int) wParam)
{
HideTooltip();
// ReSharper disable PossibleInvalidOperationException
Point cursorPosition = new Point(hookStruct.Value.pt.x, hookStruct.Value.pt.y);
// ReSharper restore PossibleInvalidOperationException
bool reRender = false;
if (_tornTab != null && _dropAreas != null)
{
// ReSharper disable ForCanBeConvertedToForeach
for (int i = 0; i < _dropAreas.Length; i++)
// ReSharper restore ForCanBeConvertedToForeach
{
// If the cursor is within the drop area, combine the tab for the window that belongs to that drop area
if (_dropAreas[i].Item2.Contains(cursorPosition))
{
TitleBarTab tabToCombine = null;
lock (_tornTabLock)
{
if (_tornTab != null)
{
tabToCombine = _tornTab;
_tornTab = null;
}
}
if (tabToCombine != null)
{
int i1 = i;
// In all cases where we need to affect the UI, we call Invoke so that those changes are made on the main UI thread since
// we are on a separate processing thread in this case
Invoke(
new Action(
() =>
{
_dropAreas[i1].Item1.TabRenderer.CombineTab(tabToCombine, cursorPosition);
tabToCombine = null;
_tornTabForm.Close();
_tornTabForm = null;
if (_parentForm.Tabs.Count == 0)
{
_parentForm.Close();
}
}));
}
}
}
}
else if (!_parentForm.TabRenderer.IsTabRepositioning)
{
StartTooltipTimer();
Point relativeCursorPosition = GetRelativeCursorPosition(cursorPosition);
// If we were over a close button previously, check to see if the cursor is still over that tab's
// close button; if not, re-render
if (_isOverCloseButtonForTab != -1 &&
(_isOverCloseButtonForTab >= _parentForm.Tabs.Count ||
!_parentForm.TabRenderer.IsOverCloseButton(_parentForm.Tabs[_isOverCloseButtonForTab], relativeCursorPosition)))
{
reRender = true;
_isOverCloseButtonForTab = -1;
}
// Otherwise, see if any tabs' close button is being hovered over
else
{
// ReSharper disable ForCanBeConvertedToForeach
for (int i = 0; i < _parentForm.Tabs.Count; i++)
// ReSharper restore ForCanBeConvertedToForeach
{
if (_parentForm.TabRenderer.IsOverCloseButton(_parentForm.Tabs[i], relativeCursorPosition))
{
_isOverCloseButtonForTab = i;
reRender = true;
break;
}
}
}
if (_isOverCloseButtonForTab == -1 && _parentForm.TabRenderer.RendersEntireTitleBar)
{
if (_parentForm.TabRenderer.IsOverSizingBox(relativeCursorPosition))
{
_isOverSizingBox = true;
reRender = true;
}
else if (_isOverSizingBox)
{
_isOverSizingBox = false;
reRender = true;
}
}
if (_parentForm.TabRenderer.IsOverAddButton(relativeCursorPosition))
{
_isOverAddButton = true;
reRender = true;
}
else if (_isOverAddButton)
{
_isOverAddButton = false;
reRender = true;
}
}
else
{
Invoke(
new Action(
() =>
{
_wasDragging = true;
// When determining if a tab has been torn from the window while dragging, we take the drop area for this window and inflate it by the
// TabTearDragDistance setting
Rectangle dragArea = TabDropArea;
dragArea.Inflate(_parentForm.TabRenderer.TabTearDragDistance, _parentForm.TabRenderer.TabTearDragDistance);
// If the cursor is outside the tear area, tear it away from the current window
if (!dragArea.Contains(cursorPosition) && _tornTab == null)
{
lock (_tornTabLock)
{
if (_tornTab == null)
{
_parentForm.TabRenderer.IsTabRepositioning = false;
// Clear the event handler subscriptions from the tab and then create a thumbnail representation of it to use when dragging
_tornTab = _parentForm.SelectedTab;
_tornTab.ClearSubscriptions();
_tornTabForm = new TornTabForm(_tornTab, _parentForm.TabRenderer);
}
}
if (_tornTab != null)
{
_parentForm.SelectedTabIndex = (_parentForm.SelectedTabIndex == _parentForm.Tabs.Count - 1
? _parentForm.SelectedTabIndex - 1
: _parentForm.SelectedTabIndex + 1);
_parentForm.Tabs.Remove(_tornTab);
// If this tab was the only tab in the window, hide the parent window
if (_parentForm.Tabs.Count == 0)
{
_parentForm.Hide();
}
_tornTabForm.Show();
_dropAreas = (from window in _parentForm.ApplicationContext.OpenWindows.Where(w => w.Tabs.Count > 0)
select new Tuple<TitleBarTabs, Rectangle>(window, window.TabDropArea)).ToArray();
}
}
}));
}
Invoke(new Action(() => OnMouseMove(new MouseEventArgs(MouseButtons.None, 0, cursorPosition.X, cursorPosition.Y, 0))));
if (_parentForm.TabRenderer.IsTabRepositioning)
{
reRender = true;
}
if (reRender)
{
Invoke(new Action(() => Render(cursorPosition, true)));
}
}
else if (nCode >= 0 && (int) WM.WM_LBUTTONDBLCLK == (int) wParam)
{
if (DesktopBounds.Contains(_lastTwoClickCoordinates[0]) && DesktopBounds.Contains(_lastTwoClickCoordinates[1]))
{
Invoke(new Action(() =>
{
_parentForm.WindowState = _parentForm.WindowState == FormWindowState.Maximized
? FormWindowState.Normal
: FormWindowState.Maximized;
}));
}
}
else if (nCode >= 0 && (int) WM.WM_LBUTTONDOWN == (int) wParam)
{
if (!_firstClick)
{
_lastTwoClickCoordinates[1] = _lastTwoClickCoordinates[0];
}
_lastTwoClickCoordinates[0] = Cursor.Position;
_firstClick = false;
_wasDragging = false;
}
else if (nCode >= 0 && (int) WM.WM_LBUTTONUP == (int) wParam)
{
// If we released the mouse button while we were dragging a torn tab, put that tab into a new window
if (_tornTab != null)
{
TitleBarTab tabToRelease = null;
lock (_tornTabLock)
{
if (_tornTab != null)
{
tabToRelease = _tornTab;
_tornTab = null;
}
}
if (tabToRelease != null)
{
Invoke(
new Action(
() =>
{
TitleBarTabs newWindow = (TitleBarTabs) Activator.CreateInstance(_parentForm.GetType());
// Set the initial window position and state properly
if (newWindow.WindowState == FormWindowState.Maximized)
{
Screen screen = Screen.AllScreens.First(s => s.WorkingArea.Contains(Cursor.Position));
newWindow.StartPosition = FormStartPosition.Manual;
newWindow.WindowState = FormWindowState.Normal;
newWindow.Left = screen.WorkingArea.Left;
newWindow.Top = screen.WorkingArea.Top;
newWindow.Width = screen.WorkingArea.Width;
newWindow.Height = screen.WorkingArea.Height;
}
else
{
newWindow.Left = Cursor.Position.X;
newWindow.Top = Cursor.Position.Y;
}
tabToRelease.Parent = newWindow;
_parentForm.ApplicationContext.OpenWindow(newWindow);
newWindow.Show();
newWindow.Tabs.Add(tabToRelease);
newWindow.SelectedTabIndex = 0;
newWindow.ResizeTabContents();
_tornTabForm.Close();
_tornTabForm = null;
if (_parentForm.Tabs.Count == 0)
{
_parentForm.Close();
}
}));
}
}
Invoke(new Action(() => OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, Cursor.Position.X, Cursor.Position.Y, 0))));
}
}
}
/// <summary>Hook callback to process <see cref="WM.WM_MOUSEMOVE" /> messages to highlight/un-highlight the close button on each tab.</summary>
/// <param name="nCode">The message being received.</param>
/// <param name="wParam">Additional information about the message.</param>
/// <param name="lParam">Additional information about the message.</param>
/// <returns>A zero value if the procedure processes the message; a nonzero value if the procedure ignores the message.</returns>
protected IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
MouseEvent mouseEvent = new MouseEvent
{
nCode = nCode,
wParam = wParam,
lParam = lParam
};
if (nCode >= 0 && (int) WM.WM_MOUSEMOVE == (int) wParam)
{
mouseEvent.MouseData = (MSLLHOOKSTRUCT) Marshal.PtrToStructure(lParam, typeof (MSLLHOOKSTRUCT));
}
_mouseEvents.Add(mouseEvent);
if (nCode >= 0 && (int) WM.WM_LBUTTONDOWN == (int) wParam)
{
long currentTicks = DateTime.Now.Ticks;
if (_lastLeftButtonClickTicks > 0 && currentTicks - _lastLeftButtonClickTicks < _doubleClickInterval * 10000)
{
_mouseEvents.Add(new MouseEvent
{
nCode = nCode,
wParam = new IntPtr((int) WM.WM_LBUTTONDBLCLK),
lParam = lParam
});
}
_lastLeftButtonClickTicks = currentTicks;
}
return User32.CallNextHookEx(_hookId, nCode, wParam, lParam);
}
/// <summary>Draws the titlebar background behind the tabs if Aero glass is not enabled.</summary>
/// <param name="graphics">Graphics context with which to draw the background.</param>
protected virtual void DrawTitleBarBackground(Graphics graphics)
{
if (DisplayType == DisplayType.Aero)
{
return;
}
Rectangle fillArea;
if (DisplayType == DisplayType.Basic)
{
fillArea = new Rectangle(
new Point(
1, Top == 0
? SystemInformation.CaptionHeight - 1
: (SystemInformation.CaptionHeight + SystemInformation.VerticalResizeBorderThickness) - (Top - _parentForm.Top) - 1),
new Size(Width - 2, _parentForm.Padding.Top));
}
else
{
fillArea = new Rectangle(new Point(1, 0), new Size(Width - 2, Height - 1));
}
if (fillArea.Height <= 0)
{
return;
}
// Adjust the margin so that the gradient stops immediately prior to the control box in the titlebar
int rightMargin = 3;
if (_parentForm.ControlBox && _parentForm.MinimizeBox)
{
rightMargin += SystemInformation.CaptionButtonSize.Width;
}
if (_parentForm.ControlBox && _parentForm.MaximizeBox)
{
rightMargin += SystemInformation.CaptionButtonSize.Width;
}
if (_parentForm.ControlBox)
{
rightMargin += SystemInformation.CaptionButtonSize.Width;
}
LinearGradientBrush gradient = new LinearGradientBrush(
new Point(24, 0), new Point(fillArea.Width - rightMargin + 1, 0), TitleBarColor, TitleBarGradientColor);
using (BufferedGraphics bufferedGraphics = BufferedGraphicsManager.Current.Allocate(graphics, fillArea))
{
bufferedGraphics.Graphics.FillRectangle(new SolidBrush(TitleBarColor), fillArea);
bufferedGraphics.Graphics.FillRectangle(
new SolidBrush(TitleBarGradientColor),
new Rectangle(new Point(fillArea.Location.X + fillArea.Width - rightMargin, fillArea.Location.Y), new Size(rightMargin, fillArea.Height)));
bufferedGraphics.Graphics.FillRectangle(
gradient, new Rectangle(fillArea.Location, new Size(fillArea.Width - rightMargin, fillArea.Height)));
bufferedGraphics.Graphics.FillRectangle(new SolidBrush(TitleBarColor), new Rectangle(fillArea.Location, new Size(24, fillArea.Height)));
bufferedGraphics.Render(graphics);
}
}
/// <summary>
/// Event handler that is called when <see cref="_parentForm" />'s <see cref="Control.SystemColorsChanged" /> event is fired which re-renders
/// the tabs.
/// </summary>
/// <param name="sender">Object from which the event originated.</param>
/// <param name="e">Arguments associated with the event.</param>
private void _parentForm_SystemColorsChanged(object sender, EventArgs e)
{
_aeroEnabled = _parentForm.IsCompositionEnabled;
OnPosition();
}
/// <summary>
/// Event handler that is called when <see cref="_parentForm" />'s <see cref="Control.SizeChanged" />, <see cref="Control.VisibleChanged" />, or
/// <see cref="Control.Move" /> events are fired which re-renders the tabs.
/// </summary>
/// <param name="sender">Object from which the event originated.</param>
/// <param name="e">Arguments associated with the event.</param>
private void _parentForm_Refresh(object sender, EventArgs e)
{
if (_parentForm.WindowState == FormWindowState.Minimized)
{
Visible = false;
}
else
{
OnPosition();
}
}
/// <summary>Sets the position of the overlay window to match that of <see cref="_parentForm" /> so that it moves in tandem with it.</summary>
protected void OnPosition()
{
if (!IsDisposed)
{
// 92 is SM_CXPADDEDBORDER, which returns the amount of extra border padding around captioned windows
int borderPadding = DisplayType == DisplayType.Classic
? 0
: User32.GetSystemMetrics(92);
// If the form is in a non-maximized state, we position the tabs below the minimize/maximize/close
// buttons
Top = _parentForm.Top + (DisplayType == DisplayType.Classic
? SystemInformation.VerticalResizeBorderThickness
: _parentForm.WindowState == FormWindowState.Maximized
? SystemInformation.VerticalResizeBorderThickness + borderPadding
: _parentForm.TabRenderer.RendersEntireTitleBar
? _parentForm.TabRenderer.IsWindows10
? SystemInformation.BorderSize.Width
: 0
: borderPadding);
Left = _parentForm.Left + SystemInformation.HorizontalResizeBorderThickness - (_parentForm.TabRenderer.IsWindows10 ? 0 : SystemInformation.BorderSize.Width) + borderPadding;
Width = _parentForm.Width - ((SystemInformation.VerticalResizeBorderThickness + borderPadding) * 2) + (_parentForm.TabRenderer.IsWindows10 ? 0 : (SystemInformation.BorderSize.Width * 2));
Height = _parentForm.TabRenderer.TabHeight + (DisplayType == DisplayType.Classic && _parentForm.WindowState != FormWindowState.Maximized && !_parentForm.TabRenderer.RendersEntireTitleBar
? SystemInformation.CaptionButtonSize.Height
: _parentForm.TabRenderer.IsWindows10
? -1 * SystemInformation.BorderSize.Width
: _parentForm.WindowState != FormWindowState.Maximized
? borderPadding
: 0);
Render();
}
}
/// <summary>
/// Renders the tabs and then calls <see cref="User32.UpdateLayeredWindow" /> to blend the tab content with the underlying window (
/// <see cref="_parentForm" />).
/// </summary>
/// <param name="forceRedraw">Flag indicating whether a full render should be forced.</param>
public void Render(bool forceRedraw = false)
{
Render(Cursor.Position, forceRedraw);
}
/// <summary>
/// Renders the tabs and then calls <see cref="User32.UpdateLayeredWindow" /> to blend the tab content with the underlying window (
/// <see cref="_parentForm" />).
/// </summary>
/// <param name="cursorPosition">Current position of the cursor.</param>
/// <param name="forceRedraw">Flag indicating whether a full render should be forced.</param>
public void Render(Point cursorPosition, bool forceRedraw = false)
{
if (!IsDisposed && _parentForm.TabRenderer != null && _parentForm.WindowState != FormWindowState.Minimized && _parentForm.ClientRectangle.Width > 0)
{
cursorPosition = GetRelativeCursorPosition(cursorPosition);
using (Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppArgb))
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
DrawTitleBarBackground(graphics);
// Since classic mode themes draw over the *entire* titlebar, not just the area immediately behind the tabs, we have to offset the tabs
// when rendering in the window
Point offset = _parentForm.WindowState != FormWindowState.Maximized && DisplayType == DisplayType.Classic && !_parentForm.TabRenderer.RendersEntireTitleBar
? new Point(0, SystemInformation.CaptionButtonSize.Height)
: _parentForm.WindowState != FormWindowState.Maximized && !_parentForm.TabRenderer.RendersEntireTitleBar
? new Point(0, SystemInformation.VerticalResizeBorderThickness - SystemInformation.BorderSize.Height)
: new Point(0, 0);
// Render the tabs into the bitmap
_parentForm.TabRenderer.Render(_parentForm.Tabs, graphics, offset, cursorPosition, forceRedraw);
// Cut out a hole in the background so that the control box on the underlying window can be shown
if (DisplayType == DisplayType.Classic && (_parentForm.ControlBox || _parentForm.MaximizeBox || _parentForm.MinimizeBox))
{
int boxWidth = 0;
if (_parentForm.ControlBox)
{
boxWidth += SystemInformation.CaptionButtonSize.Width;
}
if (_parentForm.MinimizeBox)
{
boxWidth += SystemInformation.CaptionButtonSize.Width;
}
if (_parentForm.MaximizeBox)
{
boxWidth += SystemInformation.CaptionButtonSize.Width;
}
CompositingMode oldCompositingMode = graphics.CompositingMode;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.FillRectangle(
new SolidBrush(Color.Transparent), Width - boxWidth, 0, boxWidth, SystemInformation.CaptionButtonSize.Height);
graphics.CompositingMode = oldCompositingMode;
}
IntPtr screenDc = User32.GetDC(IntPtr.Zero);
IntPtr memDc = Gdi32.CreateCompatibleDC(screenDc);
IntPtr oldBitmap = IntPtr.Zero;
IntPtr bitmapHandle = IntPtr.Zero;
try
{
// Copy the contents of the bitmap into memDc
bitmapHandle = bitmap.GetHbitmap(Color.FromArgb(0));
oldBitmap = Gdi32.SelectObject(memDc, bitmapHandle);
SIZE size = new SIZE
{
cx = bitmap.Width,
cy = bitmap.Height
};
POINT pointSource = new POINT
{
x = 0,
y = 0
};
POINT topPos = new POINT
{
x = Left,
y = Top
};
BLENDFUNCTION blend = new BLENDFUNCTION
{
// We want to blend the bitmap's content with the screen content under it
BlendOp = Convert.ToByte((int) AC.AC_SRC_OVER),
BlendFlags = 0,
// Follow the parent forms' opacity level
SourceConstantAlpha = (byte)(_parentForm.Opacity * 255),
// We use the bitmap's alpha channel for blending instead of a pre-defined transparency key
AlphaFormat = Convert.ToByte((int) AC.AC_SRC_ALPHA)
};
// Blend the tab content with the underlying content
if (!User32.UpdateLayeredWindow(
Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, ULW.ULW_ALPHA))
{
int error = Marshal.GetLastWin32Error();
throw new Win32Exception(error, "Error while calling UpdateLayeredWindow().");
}
}
// Clean up after ourselves
finally
{
User32.ReleaseDC(IntPtr.Zero, screenDc);
if (bitmapHandle != IntPtr.Zero)
{
Gdi32.SelectObject(memDc, oldBitmap);
Gdi32.DeleteObject(bitmapHandle);
}
Gdi32.DeleteDC(memDc);
}
}
}
}
}
/// <summary>Gets the relative location of the cursor within the overlay.</summary>
/// <param name="cursorPosition">Cursor position that represents the absolute position of the cursor on the screen.</param>
/// <returns>The relative location of the cursor within the overlay.</returns>
public Point GetRelativeCursorPosition(Point cursorPosition)
{
return new Point(cursorPosition.X - Location.X, cursorPosition.Y - Location.Y);
}
/// <summary>Overrides the message pump for the window so that we can respond to click events on the tabs themselves.</summary>
/// <param name="m">Message received by the pump.</param>
protected override void WndProc(ref Message m)
{
switch ((WM) m.Msg)
{
case WM.WM_SYSCOMMAND:
if (m.WParam == new IntPtr(0xF030) || m.WParam == new IntPtr(0xF120) || m.WParam == new IntPtr(0xF020))
{
_parentForm.ForwardMessage(ref m);
}
else
{
base.WndProc(ref m);
}
break;
case WM.WM_NCLBUTTONDOWN:
case WM.WM_LBUTTONDOWN:
Point relativeCursorPosition = GetRelativeCursorPosition(Cursor.Position);
// If we were over a tab, set the capture state for the window so that we'll actually receive a WM_LBUTTONUP message
if (_parentForm.TabRenderer.OverTab(_parentForm.Tabs, relativeCursorPosition) == null &&
!_parentForm.TabRenderer.IsOverAddButton(relativeCursorPosition))
{
_parentForm.ForwardMessage(ref m);
}
else
{
// When the user clicks a mouse button, save the tab that the user was over so we can respond properly when the mouse button is released
TitleBarTab clickedTab = _parentForm.TabRenderer.OverTab(_parentForm.Tabs, relativeCursorPosition);
if (clickedTab != null)