tx
2025-04-14 c33f54888d8fb4e1961bca69fe3d01e87fc54be6
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
// *********************************
// Message from Original Author:
//
// 2008 Jose Menendez Poo
// Please give me credit if you use this code. It's all I ask.
// Contact me for more info: menendezpoo@gmail.com
// *********************************
//
// Original project from http://ribbon.codeplex.com/
// Continue to support and maintain by http://officeribbon.codeplex.com/
 
 
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Security.Permissions;
using System.Windows.Forms.RibbonHelpers;
 
namespace System.Windows.Forms
{
    /// <summary>
    /// Provides a Ribbon toolbar
    /// </summary>
    [Designer(typeof(RibbonDesigner))]
    public class Ribbon
         : Control, IMessageFilter
    {
        private delegate void HandlerCallbackMethode();
 
        #region Const
 
        public const string Version = "5.0";
 
        private const int DefaultTabSpacing = 6;
        private const int DefaultPanelSpacing = 3;
 
        #endregion
 
        #region Static
 
        public static int CaptionBarHeight = 24;
 
        #endregion
 
        #region Fields
        private int _contextspace = 0;
        private bool? _isopeninvisualstudiodesigner;
        internal bool ForceOrbMenu;
        private Size _lastSizeMeasured;
        private Padding _tabsMargin;
        internal bool _minimized = true;//is the ribbon minimized?
        internal bool _expanded; //is the ribbon currently expanded when in minimize mode
        internal bool _expanding; //is the ribbon expanding. Flag used to prevent calling methods multiple time while the size changes
                                  //private int _minimizedHeight;//height when minimized
        private int _expandedHeight; //height when expanded
        private RibbonRenderer _renderer;
        private bool _useAlwaysStandardTheme;
        private Theme _theme;
        private Padding _panelMargin;
        private RibbonTab _activeTab;
        private RibbonTab _lastSelectedTab;
 
        //private float _tabSum;
        private bool _updatingSuspended;
        private bool _orbSelected;
        private bool _orbPressed;
        private bool _orbVisible;
        private Image _orbImage;
        private string _orbText;
        private Size _orbTextSize = Size.Empty;
 
        //private bool _quickAcessVisible;
        private RibbonWindowMode _borderMode;
        private GlobalHook _mouseHook;
        private GlobalHook _keyboardHook;
        private Font _RibbonItemFont = new Font("Trebuchet MS", 9);
        private Font _RibbonTabFont = new Font("Trebuchet MS", 9);
        private bool _CaptionBarVisible;
        private bool _enabled;
 
        internal RibbonItem ActiveTextBox; //tracks the current active textbox so we can hide it when you click off it
        #endregion
 
        #region Events
 
        /// <summary>
        /// Occours when the Orb is clicked
        /// </summary>
        public event EventHandler OrbClicked;
 
        /// <summary>
        /// Occours when the Orb is double-clicked
        /// </summary>
        public event EventHandler OrbDoubleClick;
 
        /// <summary>
        /// Occours when the <see cref="ActiveTab"/> property value has changed
        /// </summary>
        public event EventHandler ActiveTabChanged;
 
        /// <summary>
        /// Occours when the <see cref="ActualBorderMode"/> property has changed
        /// </summary>
        public event EventHandler ActualBorderModeChanged;
 
        /// <summary>
        /// Occours when the <see cref="CaptionButtonsVisible"/> property value has changed
        /// </summary>
        public event EventHandler CaptionButtonsVisibleChanged;
 
        ///// <summary>
        ///// Occours when the Ribbon changes its miminized state
        ///// </summary>
        public event EventHandler ExpandedChanged;
 
        #endregion
 
        #region Ctor
 
        /// <summary>
        /// Creates a new Ribbon control
        /// </summary>
        public Ribbon()
        {
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.Selectable, false);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
 
            Dock = DockStyle.Top;
 
            Tabs = new RibbonTabCollection(this);
            Contexts = new RibbonContextCollection(this);
 
            OrbsPadding = new Padding(8, 5, 8, 3);
            TabsPadding = new Padding(8, 5, 8, 3);
            _tabsMargin = new Padding(12, 24 + 2, 20, 0);
            TabTextMargin = new Padding(4, 2, 4, 2);
 
            TabContentMargin = new Padding(1, 0, 1, 2);
            PanelPadding = new Padding(3);
            _panelMargin = new Padding(3, 2, 3, 15);
            PanelMoreMargin = new Padding(0, 0, 1, 1);
            PanelSpacing = DefaultPanelSpacing;
            ItemPadding = new Padding(1, 0, 1, 0);
            ItemMargin = new Padding(4, 2, 4, 2);
            ItemImageToTextSpacing = 3;
            TabSpacing = DefaultTabSpacing;
            DropDownMargin = new Padding(2);
            _renderer = new RibbonProfessionalRenderer(this);
            _orbVisible = true;
            OrbDropDown = new RibbonOrbDropDown(this);
            QuickAccessToolbar = new RibbonQuickAccessToolbar(this);
            //_quickAcessVisible = true;
            MinimizeButton = new RibbonCaptionButton(RibbonCaptionButton.CaptionButton.Minimize);
            MaximizeRestoreButton = new RibbonCaptionButton(RibbonCaptionButton.CaptionButton.Maximize);
            CloseButton = new RibbonCaptionButton(RibbonCaptionButton.CaptionButton.Close);
            LayoutHelper = new LayoutHelper(this);
 
            MinimizeButton.SetOwner(this);
            MaximizeRestoreButton.SetOwner(this);
            CloseButton.SetOwner(this);
            _CaptionBarVisible = true;
 
            Font = SystemFonts.CaptionFont;
 
            BorderMode = RibbonWindowMode.NonClientAreaGlass;
 
            _minimized = false;
            _expanded = true;
            _enabled = true;
 
            RibbonPopupManager.PopupRegistered += OnPopupRegistered;
            RibbonPopupManager.PopupUnRegistered += OnPopupUnregistered;
            Control parent = null;
            ParentChanged += (o1, e1) =>
            {
                if (parent != null)
                {
                    parent.KeyUp -= Ribbon_KeyUp;
                    parent.KeyDown -= parent_KeyDown;
                }
 
                parent = Parent;
 
                Application.AddMessageFilter(this);
 
                if (parent is Form)
                {
                    var form = parent as Form;
 
                    form.KeyPreview = true;
 
                    form.FormClosing += (o, e) =>
                    {
                        Application.RemoveMessageFilter(this);
                    };
                }
                if (parent != null)
                {
                    parent.KeyDown += parent_KeyDown;
                    parent.KeyUp += Ribbon_KeyUp;
                }
            };
        }
 
        public bool PreFilterMessage(ref Message m)
        {
 
            // Handle Alt - KeyUp
            const int WM_SYSKEYUP = 261;
 
            if (m.Msg == WM_SYSKEYUP)
            {
                AltPressed = false;
                Invalidate();
            }
 
            return false;
        }
 
        internal bool AltPressed;
 
        private void parent_KeyDown(object sender, KeyEventArgs e)
        {
            //var reDraw = false;
 
            //if (AltPressed != e.Alt)
            //{
 
            //    reDraw = true;
            //}
 
            AltPressed = e.Alt;
 
            //if (reDraw)
            Invalidate();
        }
 
        // Function to check if item was targeted by AltKey            
        private bool IsTargetedAltKey(string key, string altKey)
        {
            if (!String.IsNullOrEmpty(key) && String.Equals(key, altKey, StringComparison.InvariantCultureIgnoreCase))
                return true;
            return false;
 
        }
 
        // Choose an action for the selected item
        private void ParseItem(RibbonItem item)
        {
            //if (item is RibbonDropDown)
            //    (item as RibbonDropDown).Focus();
            //else 
            if (item is RibbonButton)
                (item as RibbonButton).PerformClick();
            else if (item is RibbonCheckBox)
                (item as RibbonCheckBox).Checked = !(item as RibbonCheckBox).Checked;
            else if (item is RibbonTextBox)
                (item as RibbonTextBox).SetSelected(true);
        }
 
        public void Ribbon_KeyUp(object sender, KeyEventArgs e)
        {
 
            // character on key up
            var char1 = (new KeysConverter().ConvertToString(e.KeyValue));
 
            if (e.Alt && e.KeyValue > 0)
            {
 
                var ribbon1 = this;
 
                if (ribbon1.OrbPressed)
                {
                    #region Check in Orb Menus
                    foreach (var item in ribbon1.OrbDropDown.MenuItems)
                    {
 
                        if (IsTargetedAltKey(item.AltKey, char1))
                        {
 
                            ParseItem(item);
                            goto done;
                        }
                    }
                    #endregion
                }
 
                if (ribbon1.ActiveTab != null)
                {
                    #region Check in Selected Tab
                    foreach (var panel in ribbon1.ActiveTab.Panels)
                    {
                        foreach (var item in panel.GetItems())
                        {
 
                            if (IsTargetedAltKey(item.AltKey, char1))
                            {
 
                                ParseItem(item);
                                goto done;
                            }
                        }
                    }
                    #endregion
                }
 
                if (IsTargetedAltKey(ribbon1.AltKey, char1))
                {
                    ribbon1.ShowOrbDropDown();
                    goto done;
                }
 
                #region Check Tabs
                foreach (var tab in ribbon1.Tabs)
                {
                    if (IsTargetedAltKey(tab.AltKey, char1))
                    {
                        ribbon1.ActiveTab = tab;
                        goto done;
                    }
                }
                #endregion
 
                done:;
 
            }
 
            //AltPressed = false;
            //Invalidate();
        }
 
        /// <summary>
        /// Ribbon is open in Visual Studio Designer
        /// </summary>
        protected bool IsOpenInVisualStudioDesigner()
        {
            if (!_isopeninvisualstudiodesigner.HasValue)
            {
                _isopeninvisualstudiodesigner = LicenseManager.UsageMode == LicenseUsageMode.Designtime ||
                                                this.DesignMode;
                if (!_isopeninvisualstudiodesigner.Value)
                {
                    try
                    {
                        using (var process = System.Diagnostics.Process.GetCurrentProcess())
                        {
                            _isopeninvisualstudiodesigner = process.ProcessName.ToLowerInvariant().Contains("devenv");
                        }
                    }
                    catch
                    {
                    }
                }
            }
            return _isopeninvisualstudiodesigner.Value;
        }
 
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && RibbonDesigner.Current == null)
            {
                try
                {
                    foreach (RibbonTab tab in Tabs)
                        tab.Dispose();
                }
                catch (InvalidOperationException)
                {
                    if (!IsOpenInVisualStudioDesigner())
                    {
                        throw;
                    }
                }
                OrbDropDown.Dispose();
                QuickAccessToolbar.Dispose();
                MinimizeButton.Dispose();
                MaximizeRestoreButton.Dispose();
                if (_RibbonItemFont != null)
                {
                    _RibbonItemFont.Dispose();
                }
                if (_RibbonTabFont != null)
                {
                    _RibbonTabFont.Dispose();
                }
                CloseButton.Dispose();
 
                RibbonPopupManager.PopupRegistered -= OnPopupRegistered;
                RibbonPopupManager.PopupUnRegistered -= OnPopupUnregistered;
 
                //GC.SuppressFinalize(this); //not necessary, it is called in base class
            }
 
            DisposeHooks();
 
            base.Dispose(disposing);
        }
 
        //Finalize is called by base class "System.ComponentModel.Component"
        //~Ribbon()
        //{
        //    Dispose(false);
        //}
 
        private void DisposeHooks()
        {
            if (_mouseHook != null)
            {
                _mouseHook.MouseWheel -= _mouseHook_MouseWheel;
                _mouseHook.MouseDown -= _mouseHook_MouseDown;
                _mouseHook.Dispose();
                _mouseHook = null;
            }
            if (_keyboardHook != null)
            {
                _keyboardHook.KeyDown -= _keyboardHook_KeyDown;
                _keyboardHook.Dispose();
                _keyboardHook = null;
            }
        }
 
        #endregion
 
        #region Props
 
        [RefreshProperties(RefreshProperties.All)]
        [DefaultValue(0)]
        [Category("Behavior")]
        public int ContextSpace
        {
            get => _contextspace;
            set
            {
                _contextspace = value;
                OrbStyle = OrbStyle;
            }
        }
 
        /// <summary>
        /// Gets or sets the key combination that activates this element when the Alt key was pressed
        /// </summary>
        [DefaultValue(null)]
        [Category("Behavior")]
        public string AltKey { get; set; }
 
        /// <summary>
        /// Gets or sets the tabs expanded state when in minimize mode
        /// </summary>
        [DefaultValue(true)]
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool Expanded
        {
            get => _expanded;
            set
            {
                _expanded = value;
                if (!IsDesignMode() && Minimized)
                {
                    _expanding = true;
                    if (_expanded)
                        Height = _expandedHeight;
                    else
                        Height = MinimizedHeight;
 
                    OnExpandedChanged(EventArgs.Empty);
                    if (_expanded)
                        SetUpHooks();
                    else if (!_expanded && RibbonPopupManager.PopupCount == 0)
                        DisposeHooks();
                    //UpdateRegions();
                    Invalidate();
                    _expanding = false;
                }
            }
        }
 
        [DefaultValue(true)]
        [Category("Behavior")]
        [Description("Sets if the Ribbon should be enabled")]
        public new bool Enabled
        {
            get => _enabled;
            set
            {
                _enabled = value;
                Invalidate();
                UpdateRegions();
            }
        }
 
        /// <summary>
        /// Gets the height of the ribbon when collapsed <see cref="MinimizedHeight"/>
        /// </summary>
        //[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [Browsable(false)]
        [Description("Gets the height of the ribbon when collapsed")]
        public int MinimizedHeight
        {
            get
            {
                int tabBottom = Tabs.Count > 0 ? Tabs[0].Bounds.Bottom : 0;
                return Math.Max(OrbBounds.Bottom, tabBottom) + 1;
            }
        }
 
        //[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public new Size Size
        {
            get => base.Size;
            set
            {
                base.Size = value;
                Height = value.Height;
                if (!Minimized || (!_expanding && Expanded))
                    _expandedHeight = Height;
            }
        }
 
        internal Rectangle CaptionTextBounds
        {
            get
            {
                if (RightToLeft == RightToLeft.No)
                {
                    int left = 0;
                    int right = Width - 100;
                    int contextLeft = right;
                    int contextRight = left;
                    if (OrbVisible) left = OrbBounds.Right;
                    if (QuickAccessToolbar.Visible) left = QuickAccessToolbar.Bounds.Right + 20;
                    if (QuickAccessToolbar.Visible && QuickAccessToolbar.DropDownButtonVisible) left = QuickAccessToolbar.DropDownButton.Bounds.Right;
 
                    // Determine the limits of the visible contexts
                    foreach (RibbonContext context in Contexts)
                    {
                        if (context.Visible)
                        {
                            contextLeft = Math.Min(contextLeft, context.Bounds.Left);
                            contextRight = Math.Max(contextRight, context.Bounds.Right);
                        }
                    }
 
                    /* Determine which side of the context is bigger to display the caption bar.
                     * In Word/Excel, there are always enough tabs that the left side is always big enough, but this
                     * may not be the case in the user's app. If no context is displayed, both will be the same size. */
                    Rectangle r;
                    if (contextLeft - left > right - contextRight)
                    {
                        r = Rectangle.FromLTRB(left, 0, contextLeft, CaptionBarSize);
                    }
                    else
                    {
                        r = Rectangle.FromLTRB(contextRight, 0, right, CaptionBarSize);
                    }
 
                    return r;
                }
                else
                {
                    int right = ClientRectangle.Right;
                    int left = 100;
                    int contextLeft = right;
                    int contextRight = left;
                    if (OrbVisible) right = OrbBounds.Left;
                    if (QuickAccessToolbar.Visible) right = QuickAccessToolbar.Bounds.Left - 20;
                    if (QuickAccessToolbar.Visible && QuickAccessToolbar.DropDownButtonVisible) right = QuickAccessToolbar.DropDownButton.Bounds.Left;
 
                    // Determine the limits of the visible contexts
                    foreach (RibbonContext context in Contexts)
                    {
                        if (context.Visible)
                        {
                            contextLeft = Math.Min(contextLeft, context.Bounds.Left);
                            contextRight = Math.Max(contextRight, context.Bounds.Right);
                        }
                    }
 
                    /* Determine which side of the context is bigger to display the caption bar.
                     * In Word/Excel, there are always enough tabs that the left side is always big enough, but this
                     * may not be the case in the user's app. If no context is displayed, both will be the same size. */
                    Rectangle r;
                    if (contextLeft - left > right - contextRight)
                    {
                        r = Rectangle.FromLTRB(left, 0, contextLeft, CaptionBarSize);
                    }
                    else
                    {
                        r = Rectangle.FromLTRB(contextRight, 0, right, CaptionBarSize);
                    }
 
                    return r;
                }
            }
        }
 
        /// <summary>
        /// Gets if the caption buttons are currently visible, according to the value specified in <see cref="BorderMode"/>
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool CaptionButtonsVisible { get; private set; }
 
        /// <summary>
        /// Gets the Ribbon's close button
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonCaptionButton CloseButton { get; }
 
        /// <summary>
        /// Gets the Ribbon's maximize-restore button
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonCaptionButton MaximizeRestoreButton { get; }
 
        /// <summary>
        /// Gets the Ribbon's minimize button
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonCaptionButton MinimizeButton { get; }
 
        /// <summary>
        /// Gets or sets the RibbonFormHelper object if the parent form is IRibbonForm
        /// </summary>
        [Browsable(false)]
        public RibbonFormHelper FormHelper
        {
            get
            {
                IRibbonForm irf = Parent as IRibbonForm;
 
                if (irf != null)
                {
                    return irf.Helper;
                }
 
                return null;
            }
        }
 
        /// <summary>
        /// Gets the Layout Helper
        /// </summary>
        [Browsable(false)]
        public LayoutHelper LayoutHelper { get; }
 
        /// <summary>
        /// Gets the actual <see cref="RibbonWindowMode"/> that the ribbon has. 
        /// It's value may vary from <see cref="BorderMode"/>
        /// because of computer and operative system capabilities.
        /// </summary>
        [Browsable(false)]
        public RibbonWindowMode ActualBorderMode { get; private set; }
 
        /// <summary>
        /// Gets or sets the border mode of the ribbon relative to the window where it is contained
        /// </summary>
        [DefaultValue(RibbonWindowMode.NonClientAreaGlass)]
        [Category("Appearance")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [Description("Specifies how the Ribbon is placed on the window border and the non-client area")]
        public RibbonWindowMode BorderMode
        {
            get => _borderMode;
            set
            {
                _borderMode = value;
 
                RibbonWindowMode actual = value;
 
                if (value == RibbonWindowMode.NonClientAreaGlass && !WinApi.IsGlassEnabled)
                {
                    actual = RibbonWindowMode.NonClientAreaCustomDrawn;
                }
 
                if (FormHelper == null || (value == RibbonWindowMode.NonClientAreaCustomDrawn && Environment.OSVersion.Platform != PlatformID.Win32NT))
                {
                    actual = RibbonWindowMode.InsideWindow;
                }
 
                SetActualBorderMode(actual);
            }
        }
 
        /// <summary>
        /// Gets the Orb's DropDown
        /// </summary>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Category("Orb")]
        [Browsable(true)]
        public RibbonOrbDropDown OrbDropDown { get; }
 
        /// <summary>
        /// Gets or sets the height of the Panel Caption area.
        /// </summary>
        [DefaultValue(15)]
        [Category("Appearance")]
        [Description("Gets or sets the height of the Panel Caption area")]
        public int PanelCaptionHeight
        {
            get => _panelMargin.Bottom;
            set
            {
                _panelMargin.Bottom = value;
                UpdateRegions();
                Invalidate();
            }
        }
 
        /// <summary>
        /// Gets  the QuickAcessToolbar
        /// </summary>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public RibbonQuickAccessToolbar QuickAccessToolbar { get; }
 
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Theme Theme => _theme == null ? Theme.Standard : _theme;
 
        /// <summary>
        /// Gets or sets the Style of the orb.
        /// 
        /// This is where the default values are loaded when changing the OrbStyle.
        /// </summary>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [Category("Orb")]
        [DefaultValue(RibbonOrbStyle.Office_2007)]
        public RibbonOrbStyle OrbStyle
        {
            get => Theme.Style;
            set
            {
                var changed = value != Theme.Style;
                EnsureCustomThemeCreated(value, ThemeColor);
                Theme.Style = value;
                if (value == RibbonOrbStyle.Office_2007)
                {
                    TabsPadding = new Padding(8, 4, 8, 4);
                    OrbsPadding = new Padding(8, 4, 8, 4);
                    if (CaptionBarVisible)
                    {
                        _tabsMargin = new Padding(12, CaptionBarHeight + 2 + ContextSpace, 20, 0);
                    }
                    else
                    {
                        _tabsMargin = new Padding(12, 2 + ContextSpace, 20, 0);
                    }
                    TabContentMargin = new Padding(1, 0, 2, 2);
                    TabContentPadding = new Padding(0);
                    TabSpacing = 6;
                    PanelSpacing = 4;
                    PanelPadding = new Padding(3);
                    _panelMargin = new Padding(3, 2, 3, 15);
                    PanelMoreSize = new Size(6, 6);
                    PanelMoreMargin = new Padding(0, 0, 1, 1);
                    ItemMargin = new Padding(4, 2, 4, 2);
                    ItemPadding = new Padding(1, 0, 1, 0);
                    ItemImageToTextSpacing = 4;
                    this.OrbDropDown.BorderRoundness = 8;
                }
                else if ((value == RibbonOrbStyle.Office_2010) ||
                         (value == RibbonOrbStyle.Office_2010_Extended))
                {
                    TabsPadding = new Padding(10, 3, 7, 2);
                    OrbsPadding = new Padding(17, 4, 15, 4);
                    if (CaptionBarVisible)
                    {
                        TabsMargin = new Padding(6, CaptionBarHeight + 2 + ContextSpace, 20, 0);
                    }
                    else
                    {
                        TabsMargin = new Padding(6, 2 + ContextSpace, 20, 0);
                    }
                    TabContentMargin = new Padding(0, 0, 0, 2);
                    TabContentPadding = new Padding(0);
                    TabSpacing = 3;
                    PanelSpacing = 0;
                    PanelPadding = new Padding(0, 1, 1, 1);
                    _panelMargin = new Padding(2, 2, 2, 15);
                    PanelMoreSize = new Size(6, 6);
                    PanelMoreMargin = new Padding(0, 0, 2, 0);
                    ItemMargin = new Padding(3, 2, 0, 2);
                    ItemPadding = new Padding(1, 0, 1, 0);
                    ItemImageToTextSpacing = 11;
                    this.OrbDropDown.BorderRoundness = 2;
                }
                else if (value == RibbonOrbStyle.Office_2013)
                {
                    TabsPadding = new Padding(8, 4, 8, 1);
                    OrbsPadding = new Padding(15, 3, 15, 3);
                    if (CaptionBarVisible)
                    {
                        _tabsMargin = new Padding(5, CaptionBarHeight + 2 + ContextSpace, 20, 0);
                    }
                    else
                    {
                        _tabsMargin = new Padding(5, 2 + ContextSpace, 20, 0);
                    }
                    TabContentMargin = new Padding(0, 0, 0, 2);
                    TabContentPadding = new Padding(0);
                    TabSpacing = 4;
                    PanelSpacing = 0;
                    PanelPadding = new Padding(3);
                    _panelMargin = new Padding(3, 2, 3, 15);
                    PanelMoreSize = new Size(6, 6);
                    PanelMoreMargin = new Padding(0, 0, 1, 0);
                    ItemMargin = new Padding(2, 2, 0, 2);
                    ItemPadding = new Padding(1, 0, 1, 0);
                    ItemImageToTextSpacing = 11;
                    this.OrbDropDown.BorderRoundness = 2;
                }
                UpdateRegions();
                Invalidate();
                if (changed)
                {
                    OrbStyleChanged?.Invoke(this, EventArgs.Empty);
                }
            }
        }
        public event EventHandler OrbStyleChanged;
 
        /// <summary>
        /// Gets or sets the theme of the ribbon control
        /// </summary>
        //Michael Spradlin 07/05/2013
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [Category("Appearance")]
        [DefaultValue(RibbonTheme.Normal)]
        public RibbonTheme ThemeColor
        {
            get => Theme.RibbonTheme;
            set
            {
                EnsureCustomThemeCreated(OrbStyle, value);
                Theme.RibbonTheme = value;
                OnRegionsChanged();
                Invalidate();
            }
        }
 
        /// <summary>
        /// If this value is set, you can still link a Ribbon fixed to the Standard Theme.
        /// E.g. used to statically link the theme builder form to the Standard theme which is
        /// used in the <see cref="ProToolstripRenderer"/>.
        /// </summary>
        [DefaultValue(false)]
        [Category("Appearance")]
        [Description("If this value is set, you can still link a Ribbon fixed to the Standard Theme.")]
        public bool UseAlwaysStandardTheme
        {
            get => _useAlwaysStandardTheme;
            set
            {
                _useAlwaysStandardTheme = value;
                if (value)
                {
                    _theme = null;
                }
            }
        }
 
        /// <summary>
        /// Gets or sets the Text in the orb. Only available when the OrbStyle is set to Office2010
        /// </summary>
        [DefaultValue(null)]
        [Category("Orb")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string OrbText
        {
            get => _orbText;
            set
            {
                _orbText = value;
                RecalculateOrbTextSize();
                OnRegionsChanged();
                Invalidate();
            }
        }
 
        /// <summary>
        /// Gets or sets the Image of the orb
        /// </summary>
        [DefaultValue(null)]
        [Category("Orb")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Image OrbImage
        {
            get => _orbImage;
            set { _orbImage = value; OnRegionsChanged(); Invalidate(OrbBounds); }
        }
 
        /// <summary>
        /// Gets or sets if the Ribbon should show an orb on the corner
        /// </summary>
        [DefaultValue(true)]
        [Category("Orb")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public bool OrbVisible
        {
            get => _orbVisible;
            set { _orbVisible = value; OnRegionsChanged(); }
        }
 
        /// <summary>
        /// Gets or sets if the Orb is currently selected
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool OrbSelected
        {
            get => _orbSelected;
            set { _orbSelected = value; Invalidate(OrbBounds); }
        }
 
        /// <summary>
        /// Gets or sets if the Orb is currently pressed
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool OrbPressed
        {
            get => _orbPressed;
            set { _orbPressed = value; Invalidate(OrbBounds); }
        }
 
        /// <summary>
        /// Gets the Height of the caption bar
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int CaptionBarSize => CaptionBarHeight;
 
        /// <summary>
        /// Gets the bounds of the orb
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Rectangle OrbBounds
        {
            get
            {
                if (OrbStyle == RibbonOrbStyle.Office_2007)
                {
                    if (OrbVisible && RightToLeft == RightToLeft.No && CaptionBarVisible)
                    {
                        return new Rectangle(4, 4, 36, 36);
                    }
 
                    if (OrbVisible && RightToLeft == RightToLeft.Yes && CaptionBarVisible)
                    {
                        return new Rectangle(Width - 36 - 4, 4, 36, 36);
                    }
 
                    if (RightToLeft == RightToLeft.No)
                    {
                        return new Rectangle(4, 4, 0, 0);
                    }
 
                    return new Rectangle(Width - 4, 4, 0, 0);
                }
 
                if ((OrbStyle == RibbonOrbStyle.Office_2010) || (OrbStyle == RibbonOrbStyle.Office_2010_Extended)) //Kevin Carbis - office 2010 style orb
                {
                    //Measure the string size of the button text so we know how big to make the button
                    Size contentSize = _orbTextSize;
                    //If we are using an image adjust the size
                    if (OrbImage != null)
                    {
                        contentSize.Width = Math.Max(contentSize.Width, OrbImage.Size.Width);
                        contentSize.Height = Math.Max(contentSize.Height, OrbImage.Size.Height);
                    }
 
                    if (OrbVisible && RightToLeft == RightToLeft.No)
                    {
                        return new Rectangle(1, TabsMargin.Top, contentSize.Width + OrbsPadding.Left + OrbsPadding.Right, OrbsPadding.Top + contentSize.Height + OrbsPadding.Bottom);
                    }
 
                    if (OrbVisible && RightToLeft == RightToLeft.Yes && CaptionBarVisible)
                    {
                        return new Rectangle(Width - contentSize.Width - OrbsPadding.Left - OrbsPadding.Right - 1, TabsMargin.Top, contentSize.Width + OrbsPadding.Left + OrbsPadding.Right, OrbsPadding.Top + contentSize.Height + OrbsPadding.Bottom);
                    }
 
                    if (RightToLeft == RightToLeft.No)
                    {
                        return new Rectangle(4, 4, 0, 0);
                    }
 
                    return new Rectangle(Width - 4, 4, 0, 0);
                }
                else  //Michael Spradlin - 05/03/2013 Office 2013 Style Changes
                {
                    //Measure the string size of the button text so we know how big to make the button
                    Size contentSize = _orbTextSize;
                    //If we are using an image adjust the size
                    if (OrbImage != null)
                    {
                        contentSize.Width = Math.Max(contentSize.Width, OrbImage.Size.Width);
                        contentSize.Height = Math.Max(contentSize.Height, OrbImage.Size.Height);
                    }
 
                    if (OrbVisible && RightToLeft == RightToLeft.No)
                    {
                        //Steve
                        //return new Rectangle(0, TabsMargin.Top, contentSize.Width + OrbsPadding.Left + OrbsPadding.Right, OrbsPadding.Top + contentSize.Height + OrbsPadding.Bottom);
                        return new Rectangle(0, TabsMargin.Top, contentSize.Width + OrbsPadding.Left + OrbsPadding.Right, OrbsPadding.Top + contentSize.Height + OrbsPadding.Bottom + 1);
                    }
 
                    if (OrbVisible && RightToLeft == RightToLeft.Yes && CaptionBarVisible)
                    {
                        return new Rectangle(Width - contentSize.Width - OrbsPadding.Left - OrbsPadding.Right - 4, TabsMargin.Top, contentSize.Width + OrbsPadding.Left + OrbsPadding.Right, OrbsPadding.Top + contentSize.Height + OrbsPadding.Bottom);
                    }
 
                    if (RightToLeft == RightToLeft.No)
                    {
                        return new Rectangle(4, 4, 0, 0);
                    }
 
                    return new Rectangle(Width - 4, 4, 0, 0);
                }
            }
        }
 
        /// <summary>
        /// Gets the next tab to be activated
        /// </summary>
        /// <returns></returns>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonTab NextTab
        {
            get
            {
 
                if (ActiveTab == null || Tabs.Count == 0)
                {
                    if (Tabs.Count == 0)
                        return null;
 
                    return Tabs[0];
                }
 
                int index = Tabs.IndexOf(ActiveTab);
 
                if (index == Tabs.Count - 1)
                {
                    return ActiveTab;
                }
 
                return Tabs[index + 1];
            }
        }
 
        /// <summary>
        /// Gets the next tab to be activated
        /// </summary>
        /// <returns></returns>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonTab PreviousTab
        {
            get
            {
 
                if (ActiveTab == null || Tabs.Count == 0)
                {
                    if (Tabs.Count == 0)
                        return null;
 
                    return Tabs[0];
                }
 
                int index = Tabs.IndexOf(ActiveTab);
 
                if (index == 0)
                {
                    return ActiveTab;
                }
 
                return Tabs[index - 1];
            }
        }
 
        /// <summary>
        /// Gets or sets the internal spacing between the tab and its text
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding TabTextMargin { get; set; }
 
        /// <summary> 
        /// Gets or sets the margis of the DropDowns shown by the Ribbon
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding DropDownMargin { get; set; }
 
        /// <summary>
        /// Gets or sets the external spacing of items on panels
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding ItemPadding { get; set; }
 
        /// <summary>
        /// Gets or sets the padding between the image and text on a drop down RibbonItem.
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int ItemImageToTextSpacing { get; set; }
 
        /// <summary>
        /// Gets or sets the internal spacing of items
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding ItemMargin { get; set; }
 
        /// <summary>
        /// Gets or sets the tab that is currently active
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonTab ActiveTab
        {
            get => _activeTab;
            set
            {
                RibbonTab NewTab = _activeTab;
                foreach (RibbonTab tab in Tabs)
                {
                    if (tab != value)
                    {
                        tab.SetActive(false);
                    }
                    else
                    {
                        NewTab = tab;
                    }
                }
                NewTab.SetActive(true);
 
                _activeTab = value;
 
                RemoveHelperControls();
 
                value.UpdatePanelsRegions();
 
                Invalidate();
 
                RenewSensor();
 
                OnActiveTabChanged(EventArgs.Empty);
            }
        }
 
        /// <summary>
        /// Gets or sets the spacing leaded between panels
        /// </summary>
        [DefaultValue(DefaultPanelSpacing)]
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int PanelSpacing { get; set; }
 
        /// <summary>
        /// Gets or sets the size of the panel More glyph
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Size PanelMoreSize { get; set; } = new Size(7, 7);
 
        /// <summary>
        /// Gets or sets the external spacing of panels inside of tabs
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding PanelPadding { get; set; }
 
        /// <summary>
        /// Gets or sets the internal spacing of panels inside of tabs
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding PanelMargin
        {
            get => _panelMargin;
            set => _panelMargin = value;
        }
 
        /// <summary>
        /// Gets or sets the external spacing of the More glyph
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding PanelMoreMargin { get; set; }
 
        /// <summary>
        /// Gets or sets the spacing between tabs
        /// </summary>
        [Browsable(false)]
        [DefaultValue(DefaultTabSpacing)]
        public int TabSpacing { get; set; }
 
        /// <summary>
        /// Gets the collection of RibbonTab tabs
        /// </summary>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public RibbonTabCollection Tabs { get; }
 
        /// <summary>
        /// Gets or sets a value indicating if the Ribbon supports being minimized
        /// </summary>
        [Category("Appearance")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public bool Minimized
        {
            get => _minimized;
            set
            {
                _minimized = value;
                if (!IsDesignMode())
                {
                    if (_minimized)
                    {
                        Height = MinimizedHeight;
                    }
                    else
                    {
                        Height = _expandedHeight;
                    }
                    Expanded = !Minimized;
                    UpdateRegions();
                    Invalidate();
                }
            }
        }
 
        /// <summary>
        /// Gets the collection of Contexts of this Ribbon
        /// </summary>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public RibbonContextCollection Contexts { get; }
 
        /// <summary>
        /// Gets or sets the Renderer for this Ribbon control
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public RibbonRenderer Renderer
        {
            get => _renderer;
            set
            {
                _renderer = value ?? throw new ArgumentNullException(nameof(Renderer), "Null renderer!");
                Invalidate();
            }
        }
 
        /// <summary>
        /// Gets or sets the internal spacing of the tab content pane
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding TabContentMargin { get; set; }
 
        /// <summary>
        /// Gets or sets the external spacing of the tabs content pane
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding TabContentPadding { get; set; }
 
        /// <summary>
        /// Gets a value indicating the external spacing of tabs
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding TabsMargin
        {
            get => _tabsMargin;
            set
            {
                _tabsMargin = value;
                UpdateRegions();
                Invalidate();
            }
        }
 
        /// <summary>
        /// Gets a value indicating the internal spacing of tabs
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding TabsPadding { get; set; }
 
        /// <summary>
        /// Gets a value indicating the internal spacing of the orb
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Padding OrbsPadding { get; set; }
 
        /// <summary>
        /// Overriden. The maximum size is fixed
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override Size MaximumSize
        {
            get => new Size(0, 200);
            set
            {
                //not supported
            }
        }
 
        /// <summary>
        /// Overriden. The minimum size is fixed
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override Size MinimumSize
        {
            get => new Size(0, 27);
            set
            {
                //not supported
            }
        }
 
        /// <summary>
        /// Overriden. The default dock of the ribbon is top
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [DefaultValue(DockStyle.Top)]
        public override DockStyle Dock
        {
            get => base.Dock;
            set => base.Dock = value;
        }
 
        /// <summary>
        /// Gets or sets the current panel sensor for this ribbon
        /// </summary>
        [Browsable(false)]
        public RibbonMouseSensor Sensor { get; private set; }
 
        [DefaultValue(RightToLeft.No)]
        public override RightToLeft RightToLeft
        {
            get => base.RightToLeft;
            set
            {
                base.RightToLeft = value;
                OnRegionsChanged();
            }
        }
 
        /// <summary>
        /// sets or gets the visibility of the caption bar
        /// </summary>
        [Category("Appearance")]
        [DefaultValue(true)]
        public bool CaptionBarVisible
        {
            get => _CaptionBarVisible;
            set
            {
                _CaptionBarVisible = value;
                OrbStyle = OrbStyle;
            }
        }
 
        public override void Refresh()
        {
            try
            {
                if (IsDisposed == false)
                {
                    if (InvokeRequired)
                    {
                        HandlerCallbackMethode del = Refresh;
                        Invoke(del);
                    }
                    else
                    {
                        base.Refresh();
                    }
                }
            }
            catch (Exception)
            {
            }
        }
 
        #region cr
        private string cr => "Professional Ribbon\n\n2009 Jos?Manuel Menéndez Poo\nwww.menendezpoo.com";
 
        #endregion
 
        ///// <summary>
        ///// Gets or sets the Font associated with Ribbon Items.
        ///// </summary>
        //[DefaultValue(null)]
        //[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        //public Font RibbonItemFont
        //{
        //    get { return _RibbonItemFont; }
        //    set { _RibbonItemFont = value;}
        //}
 
 
        /// <summary>
        /// Gets or sets the Font associated with Ribbon tabs and the ORB.
        /// </summary>
        [DefaultValue(null)]
        [Category("Appearance")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Font RibbonTabFont
        {
            get => _RibbonTabFont;
            set { _RibbonTabFont = value; RecalculateOrbTextSize(); }
        }
 
        /// <summary>
        /// Specifies if a Tab is invisible in case it is the only one and the text is set to string.Empty.
        /// </summary>
        [Category("Appearance")]
        [Description("Specifies if a Tab is invisible in case it is the only one and the text is set to string.Empty.")]
        [DefaultValue(true)]
        public bool HideSingleTabIfTextEmpty { get; set; } = true;
 
        #endregion
 
        #region Handler Methods
 
        /// <summary>
        /// Resends the mousedown to PopupManager
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _mouseHook_MouseDown(object sender, MouseEventArgs e)
        {
            bool handled = false;
            if (!RectangleToScreen(OrbBounds).Contains(e.Location))
            {
                handled = RibbonPopupManager.FeedHookClick(e);
            }
            if (RectangleToScreen(Bounds).Contains(e.Location))
            {
                //they clicked inside the ribbon
                handled = true;
            }
            if (Minimized && !handled)
                Expanded = false;
        }
 
        /// <summary>
        /// Checks if MouseWheel should be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _mouseHook_MouseWheel(object sender, MouseEventArgs e)
        {
            if (!RibbonPopupManager.FeedMouseWheel(e))
            {
                if (RectangleToScreen(
                     new Rectangle(Point.Empty, Size)
                     ).Contains(e.Location))
                {
                    OnMouseWheel(e);
                }
            }
        }
 
 
        /// <summary>
        /// Raises the OrbClicked event
        /// </summary>
        /// <param name="e">event data</param>
        internal virtual void OnOrbClicked(EventArgs e)
        {
            if (OrbPressed)
            {
                RibbonPopupManager.Dismiss(RibbonPopupManager.DismissReason.ItemClicked);
            }
            else
            {
                ShowOrbDropDown();
            }
 
            if (OrbClicked != null)
            {
                OrbClicked(this, e);
            }
        }
 
        /// <summary>
        /// Raises the OrbDoubleClicked
        /// </summary>
        /// <param name="e"></param>
        internal virtual void OnOrbDoubleClicked(EventArgs e)
        {
            if (OrbDoubleClick != null)
            {
                OrbDoubleClick(this, e);
            }
        }
 
        #endregion
 
        #region Methods
 
        /// <summary>
        /// Initializes hooks
        /// </summary>
        private void SetUpHooks()
        {
            if (RibbonDesigner.Current == null)
            {
                if (_mouseHook == null)
                {
                    _mouseHook = new GlobalHook(GlobalHook.HookTypes.Mouse);
                    _mouseHook.MouseWheel += _mouseHook_MouseWheel;
                    _mouseHook.MouseDown += _mouseHook_MouseDown;
                }
 
                if (_keyboardHook == null)
                {
                    _keyboardHook = new GlobalHook(GlobalHook.HookTypes.Keyboard);
                    _keyboardHook.KeyDown += _keyboardHook_KeyDown;
                }
            }
        }
 
        private void _keyboardHook_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                RibbonPopupManager.Dismiss(RibbonPopupManager.DismissReason.EscapePressed);
            }
        }
 
        /// <summary>
        /// Shows the Orb's dropdown
        /// </summary>
        public void ShowOrbDropDown()
        {
            OrbPressed = true;
            if (RightToLeft == RightToLeft.No)
                if (OrbStyle == RibbonOrbStyle.Office_2007)
                    OrbDropDown.Show(PointToScreen(new Point(OrbBounds.X - 4, OrbBounds.Bottom - OrbDropDown.ContentMargin.Top + 2)));
                else if (OrbStyle == RibbonOrbStyle.Office_2010 || OrbStyle == RibbonOrbStyle.Office_2010_Extended || OrbStyle == RibbonOrbStyle.Office_2013)//Michael Spradlin - 05/03/2013 Office 2013 Style Changes
                    OrbDropDown.Show(PointToScreen(new Point(OrbBounds.X - 4, OrbBounds.Bottom)));
                else
                    if (OrbStyle == RibbonOrbStyle.Office_2007)
                    OrbDropDown.Show(PointToScreen(new Point(OrbBounds.Right + 4 - OrbDropDown.Width, OrbBounds.Bottom - OrbDropDown.ContentMargin.Top + 2)));
                else if (OrbStyle == RibbonOrbStyle.Office_2010 || OrbStyle == RibbonOrbStyle.Office_2010_Extended || OrbStyle == RibbonOrbStyle.Office_2013) //Michael Spradlin - 05/03/2013 Office 2013 Style Changes
                    OrbDropDown.Show(PointToScreen(new Point(OrbBounds.Right + 4 - OrbDropDown.Width, OrbBounds.Bottom)));
        }
 
        /// <summary>
        /// Shows the Orb's dropdown at the specified point.
        /// </summary>
        public void ShowOrbDropDown(Point pt)
        {
            OrbPressed = true;
            OrbDropDown.Show(PointToScreen(pt));
        }
 
        /// <summary>
        /// Drops out the old sensor and creates a new one
        /// </summary>
        private void RenewSensor()
        {
            if (ActiveTab == null)
            {
                return;
            }
 
            if (Sensor != null) Sensor.Dispose();
 
            Sensor = new RibbonMouseSensor(this, this, ActiveTab);
 
            if (CaptionButtonsVisible)
            {
                Sensor.Items.AddRange(new RibbonItem[] { CloseButton, MaximizeRestoreButton, MinimizeButton });
            }
        }
 
        /// <summary>
        /// Sets the value of the <see cref="BorderMode"/> property
        /// </summary>
        /// <param name="borderMode">Actual border mode accquired</param>
        private void SetActualBorderMode(RibbonWindowMode borderMode)
        {
            bool trigger = ActualBorderMode != borderMode;
 
            ActualBorderMode = borderMode;
 
            if (trigger)
                OnActualBorderModeChanged(EventArgs.Empty);
 
            SetCaptionButtonsVisible(borderMode == RibbonWindowMode.NonClientAreaCustomDrawn);
 
 
        }
 
        /// <summary>
        /// Sets the value of the <see cref="CaptionButtonsVisible"/> property
        /// </summary>
        /// <param name="visible">Value to set to the caption buttons</param>
        private void SetCaptionButtonsVisible(bool visible)
        {
            bool trigger = CaptionButtonsVisible != visible;
 
            CaptionButtonsVisible = visible;
 
            if (trigger)
                OnCaptionButtonsVisibleChanged(EventArgs.Empty);
        }
 
        /// <summary>
        /// Suspends any drawing/regions update operation
        /// </summary>
        public void SuspendUpdating()
        {
            _updatingSuspended = true;
        }
 
        /// <summary>
        /// Resumes any drawing/regions update operation
        /// </summary>
        ///// <param name="update"></param>
        public void ResumeUpdating()
        {
            ResumeUpdating(true);
        }
 
        /// <summary>
        /// Resumes any drawing/regions update operation
        /// </summary>
        /// <param name="update"></param>
        public void ResumeUpdating(bool update)
        {
            _updatingSuspended = false;
 
            if (update)
            {
                OnRegionsChanged();
            }
        }
 
        /// <summary>
        /// Removes all helper controls placed by any reason.
        /// Contol's visibility is set to false before removed.
        /// </summary>
        private void RemoveHelperControls()
        {
            RibbonPopupManager.Dismiss(RibbonPopupManager.DismissReason.AppClicked);
 
            while (Controls.Count > 0)
            {
                Control ctl = Controls[0];
 
                ctl.Visible = false;
 
                Controls.Remove(ctl);
            }
        }
 
        /// <summary>
        /// Hittest on tab
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns>true if a tab has been clicked</returns>
        internal bool TabHitTest(int x, int y)
        {
            //if (Rectangle.FromLTRB(Right - 10, Bottom - 10, Right, Bottom).Contains(x, y))
            //{
            //   MessageBox.Show(cr);
            //}
 
            //look for mouse on tabs
            foreach (RibbonTab tab in Tabs)
            {
                if (tab.TabBounds.Contains(x, y))
                {
                    ActiveTab = tab;
                    Expanded = true;
 
                    return true;
                }
            }
 
            return false;
        }
 
        /// <summary>
        /// Hittest on context
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns>true if a tab has been clicked</returns>
        internal bool ContextHitTest(int x, int y)
        {
            //look for mouse on context
            foreach (RibbonContext context in Contexts)
            {
                if (context.Bounds.Contains(x, y))
                {
                    return true;
                }
            }
 
            return false;
        }
 
        /// <summary>
        /// Updates the regions of the tabs and the tab content bounds of the active tab
        /// </summary>
        internal void UpdateRegions()
        {
            UpdateRegions(null);
        }
 
        /// <summary>
        /// Updates the regions of the tabs and the tab content bounds of the active tab
        /// </summary>
        internal void UpdateRegions(Graphics g)
        {
            bool graphicsCreated = false;
 
            if (IsDisposed || _updatingSuspended) return;
 
            //Graphics for measurement
            if (g == null)
            {
                g = CreateGraphics();
                graphicsCreated = true;
            }
 
            UpdateRegionsTabsConsiderRTL(g);
 
            if (RightToLeft == RightToLeft.No)
            {
                #region Update QuickAccess bounds
 
                QuickAccessToolbar.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.Compact));
                if (OrbStyle == RibbonOrbStyle.Office_2007)
                    QuickAccessToolbar.SetBounds(new Rectangle(new Point(OrbBounds.Right + QuickAccessToolbar.Margin.Left, OrbBounds.Top - 2), QuickAccessToolbar.LastMeasuredSize));
                else if ((OrbStyle == RibbonOrbStyle.Office_2010) || (OrbStyle == RibbonOrbStyle.Office_2010_Extended)) //2010 - no need to offset for the orb
                    QuickAccessToolbar.SetBounds(new Rectangle(new Point(QuickAccessToolbar.Margin.Left, 0), QuickAccessToolbar.LastMeasuredSize));
                else if (OrbStyle == RibbonOrbStyle.Office_2013) //Michael Spradlin - 05/03/2013 Office 2013 Style Changes : no need to offset for the orb
                    QuickAccessToolbar.SetBounds(new Rectangle(new Point(QuickAccessToolbar.Margin.Left, 0), QuickAccessToolbar.LastMeasuredSize));
 
                #endregion
 
                #region Update Caption Buttons bounds
 
                if (CaptionButtonsVisible)
                {
                    Size cbs = new Size(20, 20);
                    int cbg = 2;
                    CloseButton.SetBounds(new Rectangle(new Point(ClientRectangle.Right - cbs.Width - cbg, cbg), cbs));
                    MaximizeRestoreButton.SetBounds(new Rectangle(new Point(CloseButton.Bounds.Left - cbs.Width, cbg), cbs));
                    MinimizeButton.SetBounds(new Rectangle(new Point(MaximizeRestoreButton.Bounds.Left - cbs.Width, cbg), cbs));
                }
 
                #endregion
            }
            else  // RightToLeft.Yes
            {
                #region Update QuickAccess bounds
 
                QuickAccessToolbar.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.Compact));
                if (OrbStyle == RibbonOrbStyle.Office_2007)
                    QuickAccessToolbar.SetBounds(new Rectangle(new Point(OrbBounds.Left - QuickAccessToolbar.Margin.Right - QuickAccessToolbar.LastMeasuredSize.Width, OrbBounds.Top - 2), QuickAccessToolbar.LastMeasuredSize));
                else if ((OrbStyle == RibbonOrbStyle.Office_2010) || (OrbStyle == RibbonOrbStyle.Office_2010_Extended)) //2010 - no need to offset for the orb
                    QuickAccessToolbar.SetBounds(new Rectangle(new Point(ClientRectangle.Right - QuickAccessToolbar.Margin.Right - QuickAccessToolbar.LastMeasuredSize.Width, 0), QuickAccessToolbar.LastMeasuredSize));
                else if (OrbStyle == RibbonOrbStyle.Office_2013)  //Michael Spradlin - 05/03/2013 Office 2013 Style Changes: no need to offset for the orb
                    QuickAccessToolbar.SetBounds(new Rectangle(new Point(ClientRectangle.Right - QuickAccessToolbar.Margin.Right - QuickAccessToolbar.LastMeasuredSize.Width, 0), QuickAccessToolbar.LastMeasuredSize));
 
                #endregion
 
                #region Update Caption Buttons bounds
 
                if (CaptionButtonsVisible)
                {
                    Size cbs = new Size(20, 20);
                    int cbg = 2;
                    CloseButton.SetBounds(new Rectangle(new Point(ClientRectangle.Left, cbg), cbs));
                    MaximizeRestoreButton.SetBounds(new Rectangle(new Point(CloseButton.Bounds.Right, cbg), cbs));
                    MinimizeButton.SetBounds(new Rectangle(new Point(MaximizeRestoreButton.Bounds.Right, cbg), cbs));
                }
 
                #endregion
            }
 
            //Update the minimize settings
            //_minimizedHeight = tabsBottom;
 
            if (graphicsCreated)
                g.Dispose();
 
            _lastSizeMeasured = Size;
 
            RenewSensor();
        }
 
        private void UpdateRegionsTabsConsiderRTL(Graphics g)
        {
            // Saves the bottom of the tabs
            int tabsBottom = 0;
            // X coordinate reminder
            Point curXPos = new Point((RightToLeft == RightToLeft.No) ? OrbBounds.Width + TabsMargin.Left : OrbBounds.Left - TabsMargin.Left + 4, 0);
 
            // Saves the width of the larger tab
            int maxWidth = 0;
            int tabTop = 0;
 
            #region Assign default tab and unused context bounds (best case)
 
            foreach (RibbonTab tab in Tabs)
            {
                if (tab.Visible || IsDesignMode())
                {
                    Size tabSize = tab.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.None));
 
                    if (tab.Contextual && tab.Context.ContextualTabsCount == 1)
                    {
                        //Only if the context covers one tab do we need to be concerned that the context text maybe longer than the tab text.
                        Size contextSize = tab.Context.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.None));
                        tabSize.Width = Math.Max(tabSize.Width, contextSize.Width);
                    }
 
                    tabTop = (tab.Invisible == false || OrbVisible)
                       ? TabsMargin.Top
                       : TabsMargin.Top - tabSize.Height - 8 + (OrbStyle == RibbonOrbStyle.Office_2013 ? 2 : 0);
                    Rectangle bounds = new Rectangle(0, tabTop,
                           TabsPadding.Left + tabSize.Width + TabsPadding.Right,
                           TabsPadding.Top + tabSize.Height + TabsPadding.Bottom);
 
                    bounds = LayoutHelper.CalcNewPosition(curXPos, bounds, LayoutHelper.RTLLayoutPosition.Far, TabSpacing);
 
                    tab.SetTabBounds(bounds);
 
                    curXPos = LayoutHelper.CalcNewPosition(bounds, curXPos, LayoutHelper.RTLLayoutPosition.Far, 0);
 
                    maxWidth = Math.Max(bounds.Width, maxWidth);
                    tabsBottom = Math.Max(bounds.Bottom, tabsBottom);
 
                    tab.SetTabContentBounds(Rectangle.FromLTRB(
                         TabContentMargin.Left, tabsBottom + TabContentMargin.Top,
                         ClientSize.Width - TabContentMargin.Right, ClientSize.Height - TabContentMargin.Bottom));
 
                    if (tab.Active)
                    {
                        tab.UpdatePanelsRegions();
                    }
                }
                else
                {
                    tab.SetTabBounds(Rectangle.Empty);
                    tab.SetTabContentBounds(Rectangle.Empty);
                    if (tab.Contextual)
                    {
                        tab.Context.SetBounds(Rectangle.Empty);
                        tab.Context.SetHeaderBounds(Rectangle.Empty);
                    }
                }
            }
 
            foreach (RibbonContext context in Contexts)
            {
                //Include unused RibbonContexts that need to be displayed
                if ((context.ContextualTabsCount == 0) && IsDesignMode())
                {
                    Size contextSize = context.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.None));
 
                    tabTop = (context.Visible || OrbVisible)
                       ? TabsMargin.Top
                       : TabsMargin.Top - contextSize.Height - 8 + (OrbStyle == RibbonOrbStyle.Office_2013 ? 2 : 0);
 
                    Rectangle contextBounds = new Rectangle(0, tabTop - CaptionBarHeight,
                        TabsPadding.Left + contextSize.Width + TabsPadding.Right,
                        TabsPadding.Top + contextSize.Height + TabsPadding.Bottom + CaptionBarHeight);
                    Rectangle contextHeaderBounds = new Rectangle(contextBounds.Left, contextBounds.Top,
                        contextBounds.Width, CaptionBarHeight);
 
                    contextBounds = LayoutHelper.CalcNewPosition(curXPos, contextBounds, LayoutHelper.RTLLayoutPosition.Far, TabSpacing);
                    contextHeaderBounds = LayoutHelper.CalcNewPosition(curXPos, contextHeaderBounds, LayoutHelper.RTLLayoutPosition.Far, TabSpacing);
 
                    context.SetBounds(contextBounds);
                    context.SetHeaderBounds(contextHeaderBounds);
 
                    curXPos = LayoutHelper.CalcNewPosition(contextBounds, curXPos, LayoutHelper.RTLLayoutPosition.Far, 0);
 
                    maxWidth = Math.Max(contextBounds.Width, maxWidth);
                    tabsBottom = Math.Max(contextBounds.Bottom, tabsBottom);
                }
            }
 
 
            #endregion
 
            #region Reduce bounds of tabs if needed
 
            while ((RightToLeft == RightToLeft.No ? curXPos.X > ClientRectangle.Right : curXPos.X < ClientRectangle.Left)
               && maxWidth > 0)
            {
 
                curXPos = new Point((RightToLeft == RightToLeft.No) ? OrbBounds.Width + TabsMargin.Left : OrbBounds.Left - TabsMargin.Left + 4, 0);
                maxWidth--;
 
                // Shrink each tab
                foreach (RibbonTab tab in Tabs)
                {
                    if (tab.Visible)
                    {
 
                        Size tabSize = tab.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.None));
 
                        if (tabSize.Width >= maxWidth)
                        {
                            tabSize.Width = maxWidth;
                        }
 
                        if (tab.Contextual && tab.Context.ContextualTabsCount == 1)
                        {
                            //Only if the context covers one tab do we need to be concerned that the context text maybe longer than the tab text.
                            Size contextSize = tab.Context.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.None));
                            tabSize.Width = Math.Max(tabSize.Width, contextSize.Width);
                        }
 
                        tabTop = (tab.Invisible == false || OrbVisible)
                           ? TabsMargin.Top
                           : TabsMargin.Top - tabSize.Height - 8 + (OrbStyle == RibbonOrbStyle.Office_2013 ? 2 : 0);
                        Rectangle bounds = new Rectangle(0, tabTop,
                               TabsPadding.Left + tabSize.Width + TabsPadding.Right,
                               TabsPadding.Top + tabSize.Height + TabsPadding.Bottom);
 
                        bounds = LayoutHelper.CalcNewPosition(curXPos, bounds, LayoutHelper.RTLLayoutPosition.Far, TabSpacing);
 
                        tab.SetTabBounds(bounds);
 
                        curXPos = LayoutHelper.CalcNewPosition(bounds, curXPos, LayoutHelper.RTLLayoutPosition.Far, 0);
                    }
                }
 
                // Shrink each context
                foreach (RibbonContext context in Contexts)
                {
                    //Include unused RibbonContexts that need to be displayed
                    if ((context.ContextualTabsCount == 0) && IsDesignMode())
                    {
                        Size contextSize = context.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.None));
 
                        if (contextSize.Width >= maxWidth)
                        {
                            contextSize.Width = maxWidth;
                        }
 
                        tabTop = (context.Visible || OrbVisible)
                           ? TabsMargin.Top
                           : TabsMargin.Top - contextSize.Height - 8 + (OrbStyle == RibbonOrbStyle.Office_2013 ? 2 : 0);
 
                        Rectangle contextBounds = new Rectangle(0, tabTop - CaptionBarHeight,
                            TabsPadding.Left + contextSize.Width + TabsPadding.Right,
                            TabsPadding.Top + contextSize.Height + TabsPadding.Bottom + CaptionBarHeight);
                        Rectangle contextHeaderBounds = new Rectangle(contextBounds.Left, contextBounds.Top,
                            contextBounds.Width, CaptionBarHeight);
 
                        contextBounds = LayoutHelper.CalcNewPosition(curXPos, contextBounds, LayoutHelper.RTLLayoutPosition.Far, TabSpacing);
                        contextHeaderBounds = LayoutHelper.CalcNewPosition(curXPos, contextHeaderBounds, LayoutHelper.RTLLayoutPosition.Far, TabSpacing);
 
                        context.SetBounds(contextBounds);
                        context.SetHeaderBounds(contextHeaderBounds);
 
                        curXPos = LayoutHelper.CalcNewPosition(contextBounds, curXPos, LayoutHelper.RTLLayoutPosition.Far, 0);
                    }
                }
            }
 
            #endregion
 
            #region Fix the width of contexts that contain tabs
 
            foreach (RibbonContext context in Contexts)
            {
                //Define bounds for contexts
                if (context.ContextualTabsCount > 0)
                {
                    foreach (RibbonTab tab in context.ContextualTabs)
                    {
                        Rectangle firstTabBounds = context.ContextualTabs[context.ContextualTabs.Count - 1].Bounds;
                        Rectangle lastTabBounds = context.ContextualTabs[0].Bounds;
 
                        int maxRight = Math.Max(firstTabBounds.Right, lastTabBounds.Right);
                        int maxLeft = Math.Min(firstTabBounds.Left, lastTabBounds.Left);
 
                        Rectangle contextBounds = new Rectangle(maxLeft, tabTop - CaptionBarHeight,
                             (maxRight - maxLeft),
                             TabsPadding.Top + firstTabBounds.Height + TabsPadding.Bottom + CaptionBarHeight);
                        Rectangle contextHeaderBounds = new Rectangle(contextBounds.Left, contextBounds.Top,
                             contextBounds.Width, CaptionBarHeight);
 
                        tab.Context.SetBounds(contextBounds);
                        tab.Context.SetHeaderBounds(contextHeaderBounds);
                    }
                }
            }
 
            #endregion
        }
 
        /// <summary>
        /// Forces a size recalculation on the entire control
        /// </summary>
        internal void OnRegionsChanged()
        {
            if (_updatingSuspended) return;
 
            //Kevin - Fix when only one tab present and there is a textbox on it. It will loose focus after each char is entered
            //if (Tabs.Count == 1)
            if (Tabs.Count == 1 && ActiveTab != Tabs[0])
            {
                ActiveTab = Tabs[0];
            }
 
            _lastSizeMeasured = Size.Empty;
 
            Refresh();
        }
 
        /// <summary>
        /// Redraws the specified tab
        /// </summary>
        /// <param name="tab"></param>
        internal void RedrawTab(RibbonTab tab)
        {
            using (Graphics g = CreateGraphics())
            {
                Rectangle clip = Rectangle.FromLTRB(
                     tab.TabBounds.Left,
                     tab.TabBounds.Top,
                     tab.TabBounds.Right,
                     tab.TabBounds.Bottom);
 
                g.SetClip(clip);
                SmoothingMode sm = g.SmoothingMode;
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.TextRenderingHint = TextRenderingHint.AntiAlias;
                tab.OnPaint(this, new RibbonElementPaintEventArgs(tab.TabBounds, g, RibbonElementSizeMode.None));
                g.SmoothingMode = sm;
                g.TextRenderingHint = TextRenderingHint.SystemDefault;
            }
        }
 
        /// <summary>
        /// Sets the currently selected tab
        /// </summary>
        /// <param name="tab"></param>
        private void SetSelectedTab(RibbonTab tab)
        {
            if (tab == _lastSelectedTab) return;
 
            if (_lastSelectedTab != null)
            {
                _lastSelectedTab.SetSelected(false);
                RedrawTab(_lastSelectedTab);
            }
 
            if (tab != null)
            {
                tab.SetSelected(true);
                RedrawTab(tab);
            }
 
            _lastSelectedTab = tab;
 
        }
 
        /// <summary>
        /// Suspends the sensor activity
        /// </summary>
        internal void SuspendSensor()
        {
            if (Sensor != null)
                Sensor.Suspend();
        }
 
        /// <summary>
        /// Resumes the sensor activity
        /// </summary>
        internal void ResumeSensor()
        {
            Sensor.Resume();
        }
 
        /// <summary>
        /// Redraws the specified area on the sensor's control
        /// </summary>
        /// <param name="area"></param>
        public void RedrawArea(Rectangle area)
        {
            Sensor.Control.Invalidate(area);
        }
 
        /// <summary>
        /// Activates the next tab available
        /// </summary>
        public void ActivateNextTab()
        {
            RibbonTab tab = NextTab;
 
            if (tab != null)
            {
                ActiveTab = tab;
            }
        }
 
        /// <summary>
        /// Activates the previous tab available
        /// </summary>
        public void ActivatePreviousTab()
        {
            RibbonTab tab = PreviousTab;
 
            if (tab != null)
            {
                ActiveTab = tab;
            }
        }
 
        /// <summary>
        /// Handles the mouse down on the orb area
        /// </summary>
        internal void OrbMouseDown()
        {
            OnOrbClicked(EventArgs.Empty);
        }
 
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
        protected override void WndProc(ref Message m)
        {
 
            bool bypassed = false;
 
            if (WinApi.IsWindows && (ActualBorderMode == RibbonWindowMode.NonClientAreaGlass || ActualBorderMode == RibbonWindowMode.NonClientAreaCustomDrawn))
            {
                if (m.Msg == WinApi.WM_NCHITTEST) //0x84
                {
                    Form f = FindForm();
                    Rectangle caption;
 
                    if (RightToLeft == RightToLeft.No)
                    {
                        int captionLeft = QuickAccessToolbar.Visible ? QuickAccessToolbar.Bounds.Right : OrbBounds.Right;
                        if (QuickAccessToolbar.Visible && QuickAccessToolbar.DropDownButtonVisible) captionLeft = QuickAccessToolbar.DropDownButton.Bounds.Right;
                        caption = Rectangle.FromLTRB(captionLeft, 0, Width, CaptionBarSize);
                    }
                    else
                    {
                        int captionRight = QuickAccessToolbar.Visible ? QuickAccessToolbar.Bounds.Left : OrbBounds.Left;
                        if (QuickAccessToolbar.Visible && QuickAccessToolbar.DropDownButtonVisible) captionRight = QuickAccessToolbar.DropDownButton.Bounds.Left;
                        caption = Rectangle.FromLTRB(0, 0, captionRight, CaptionBarSize);
                    }
 
                    Point screenPoint = new Point(WinApi.Get_X_LParam(m.LParam), WinApi.Get_Y_LParam(m.LParam));
                    Point ribbonPoint = PointToClient(screenPoint);
                    bool onCaptionButtons = false;
 
                    if (CaptionButtonsVisible)
                    {
                        onCaptionButtons = CloseButton.Bounds.Contains(ribbonPoint) ||
                        MinimizeButton.Bounds.Contains(ribbonPoint) ||
                        MaximizeRestoreButton.Bounds.Contains(ribbonPoint);
                    }
 
                    if (RectangleToScreen(caption).Contains(screenPoint) && !onCaptionButtons)
                    {
                        //on the caption bar area
                        Point p = PointToScreen(screenPoint);
                        WinApi.SendMessage(f.Handle, WinApi.WM_NCHITTEST, m.WParam, WinApi.MakeLParam(p.X, p.Y));
                        m.Result = new IntPtr(-1);
                        bypassed = true;
                        //Kevin - fix so when you mouse off the caption buttons onto the caption area
                        //the buttons will clear the selection. same with the QAT buttons
                        CloseButton.SetSelected(false);
                        MinimizeButton.SetSelected(false);
                        MaximizeRestoreButton.SetSelected(false);
                        OrbSelected = false;
                        QuickAccessToolbar.DropDownButton.SetSelected(false);
                    }
                }
            }
 
            if (!bypassed)
            {
                base.WndProc(ref m);
            }
        }
 
        /// <summary>
        /// Paints the Ribbon on the specified device
        /// </summary>
        /// <param name="g">Device where to paint on</param>
        /// <param name="clip">Clip rectangle</param>
        private void PaintOn(Graphics g, Rectangle clip)
        {
            try
            {
                if (WinApi.IsWindows && Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                }
 
                //Caption Background
                Renderer.OnRenderRibbonBackground(new RibbonRenderEventArgs(this, g, clip));
 
                //Caption Bar
                Renderer.OnRenderRibbonCaptionBar(new RibbonRenderEventArgs(this, g, clip));
 
                //Caption Buttons
                if (CaptionButtonsVisible)
                {
                    MinimizeButton.OnPaint(this, new RibbonElementPaintEventArgs(clip, g, RibbonElementSizeMode.Medium));
                    MaximizeRestoreButton.OnPaint(this, new RibbonElementPaintEventArgs(clip, g, RibbonElementSizeMode.Medium));
                    CloseButton.OnPaint(this, new RibbonElementPaintEventArgs(clip, g, RibbonElementSizeMode.Medium));
                }
 
                //Orb
                Renderer.OnRenderRibbonOrb(new RibbonRenderEventArgs(this, g, clip));
 
                //QuickAccess toolbar
                QuickAccessToolbar.OnPaint(this, new RibbonElementPaintEventArgs(clip, g, RibbonElementSizeMode.Compact));
 
                //Render Contexts
                foreach (RibbonContext context in Contexts)
                {
                    if (context.Visible || IsDesignMode())
                    {
                        context.OnPaint(this, new RibbonElementPaintEventArgs(context.Bounds, g, RibbonElementSizeMode.None, this));
                    }
                }
 
                //Render Tabs
                foreach (RibbonTab tab in Tabs)
                {
                    if (tab.Visible || IsDesignMode())
                    {
                        tab.OnPaint(this, new RibbonElementPaintEventArgs(tab.TabBounds, g, RibbonElementSizeMode.None, this));
                    }
                }
 
                if (OrbVisible && !_expanded && !string.IsNullOrEmpty(OrbText))
                {
                    if ((OrbStyle == RibbonOrbStyle.Office_2010) ||
                        (OrbStyle == RibbonOrbStyle.Office_2010_Extended))
                    {
                        //draw the divider line at the bottom of the ribbon
                        Pen p = new Pen(Theme.RendererColorTable.TabBorder);
                        g.DrawLine(p, OrbBounds.Left, OrbBounds.Bottom, Bounds.Right, OrbBounds.Bottom);
                    }
                    else if (OrbStyle == RibbonOrbStyle.Office_2013)
                    {
                        //There is no line at the bottom of the Ribbon in Office 2013
                    }
                }
            }
            catch
            {
            }
        }
 
        private void PaintDoubleBuffered(Graphics wndGraphics, Rectangle clip)
        {
            using (Bitmap bmp = new Bitmap(Width, Height))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    g.Clear(Color.Black);
                    PaintOn(g, clip);
                    g.Flush();
 
                    WinApi.BitBlt(wndGraphics.GetHdc(), clip.X, clip.Y, clip.Width, clip.Height, g.GetHdc(), clip.X, clip.Y, WinApi.SRCCOPY);
                    //WinApi.BitBlt(wndGraphics.GetHdc(), 0, 0, Width, Height, g.GetHdc(), 0, 0, WinApi.SRCCOPY);
                }
 
                //wndGraphics.DrawImage(bmp, Point.Empty);
            }
        }
 
        internal bool IsDesignMode()
        {
            return Site != null && Site.DesignMode;
        }
 
        private void EnsureCustomThemeCreated(RibbonOrbStyle orbStyle, RibbonTheme theme)
        {
            if (_theme == null && Theme.StandardThemeIsGlobal == false && UseAlwaysStandardTheme == false)
            {
                _theme = new Theme(orbStyle, theme);
            }
        }
 
        private void RecalculateOrbTextSize()
        {
            if (string.IsNullOrEmpty(OrbText))
            {
                _orbTextSize = Size.Empty;
            }
            else
            {
                try
                {
                    using (Graphics g = CreateGraphics())
                    {
                        _orbTextSize = Size.Ceiling(g.MeasureString(OrbText, RibbonTabFont));
                    }
                }
                catch { }
            }
        }
 
        #endregion
 
        #region Event Overrides
 
        /// <summary>
        /// Raises the <see cref="ActiveTabChanged"/> event
        /// </summary>
        /// <param name="e">Event data</param>
        protected virtual void OnActiveTabChanged(EventArgs e)
        {
            if (ActiveTabChanged != null)
            {
                ActiveTabChanged(this, e);
            }
        }
 
        /// <summary>
        /// Raises the <see cref="ActualBorderMode"/> event
        /// </summary>
        /// <param name="e"></param>
        protected virtual void OnActualBorderModeChanged(EventArgs e)
        {
            if (ActualBorderModeChanged != null)
            {
                ActualBorderModeChanged(this, e);
            }
        }
 
        /// <summary>
        /// Raises the <see cref="CaptionButtonsVisibleChanged"/> event
        /// </summary>
        /// <param name="e"></param>
        protected virtual void OnCaptionButtonsVisibleChanged(EventArgs e)
        {
            if (CaptionButtonsVisibleChanged != null)
            {
                CaptionButtonsVisibleChanged(this, e);
            }
        }
 
        /// <summary>
        /// Raises the <see cref="ExpandedChanged"/> event
        /// </summary>
        /// <param name="e"></param>
        protected virtual void OnExpandedChanged(EventArgs e)
        {
            if (ExpandedChanged != null)
            {
                ExpandedChanged(this, e);
            }
        }
 
        protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            base.OnMouseDoubleClick(e);
 
            if (OrbBounds.Contains(e.Location))
            {
                OnOrbDoubleClicked(EventArgs.Empty);
            }
 
            if (Tabs.Count != 1 || Tabs[0].Invisible == false)
            {
                foreach (RibbonTab tab in Tabs)
                {
                    if (tab.Bounds.Contains(e.Location))
                    {
                        Minimized = !Minimized;
                        break;
                    }
                }
            }
        }
 
        protected override void OnPaintBackground(PaintEventArgs pevent)
        {
            //base.OnPaintBackground(pevent);
        }
 
        /// <summary>
        /// Overriden. Raises the Paint event and draws all the Ribbon content
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"></see> that contains the event data.</param>
        protected override void OnPaint(PaintEventArgs e)
        {
            if (_updatingSuspended) return;
 
            if (Size != _lastSizeMeasured)
                UpdateRegions(e.Graphics);
 
            PaintOn(e.Graphics, e.ClipRectangle);
        }
 
        /// <summary>
        /// Overriden. Raises the Click event and tunnels the message to child elements
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
        }
 
        /// <summary>
        /// Overriden. Riases the MouseEnter event and tunnels the message to child elements
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
        }
 
        /// <summary>
        /// Overriden. Raises the MouseLeave  event and tunnels the message to child elements
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            //Console.WriteLine("Ribbon Mouse Leave");
            SetSelectedTab(null);
            if (!Expanded)
                foreach (RibbonTab tab in Tabs)
                {
                    tab.SetSelected(false);
                }
            Invalidate();
        }
 
        /// <summary>
        /// Overriden. Raises the MouseMove event and tunnels the message to child elements
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"></see> that contains the event data.</param>
        protected override void OnMouseMove(MouseEventArgs e)
        {
            //Console.WriteLine("Ribbon: " + e.Location.ToString());
 
            // Kevin Carbis's new code, edited by adriancs, on behave of Carbis
            // The below fix some minor bug. The cursor is not displayed properly
            // when cursor is entering CheckBound of CheckBox and TextBox.
            // The cursor keep changing from Cursors.Default to Cursors.Hand a few times
            // within a second.
            // The below code is obtain from Kcarbis's website
            #region Kevin Carbis's new code, edited by adriancs
            base.OnMouseMove(e);
 
            if (ActiveTab == null) return;
 
            bool someTabHitted = false;
 
            //Check if mouse on tab
            if (ActiveTab.TabContentBounds.Contains(e.X, e.Y))
            {
                //Do nothing, everything is on the sensor
            }
            //Check if mouse on orb
            else if (OrbVisible && OrbBounds.Contains(e.Location) && !OrbSelected)
            {
                OrbSelected = true;
                Invalidate(OrbBounds);
            }
            //Check if mouse on QuickAccess toolbar
            else if (QuickAccessToolbar.Visible && QuickAccessToolbar.Bounds.Contains(e.Location))
            {
 
            }
            else
            {
                //look for mouse on tabs
                foreach (RibbonTab tab in Tabs)
                {
                    if (tab.TabBounds.Contains(e.X, e.Y))
                    {
                        SetSelectedTab(tab);
                        someTabHitted = true;
                        tab.OnMouseMove(e);
                    }
                }
            }
 
            if (!someTabHitted)
                SetSelectedTab(null);
 
            if (OrbSelected && !OrbBounds.Contains(e.Location))
            {
                OrbSelected = false;
                Invalidate(OrbBounds);
            }
            #endregion
 
            #region Kevin Carbis's old code, commented out by adriancs
            //base.OnMouseMove(e);
 
            ////Kevin Carbis - Need to reset the curor here so we can pickup the cursor when it moves off of an active textbox.  If we don't we will
            ////have the IBeam cursor over the entire ribbon.
            //Cursor.Current = Cursors.Default;
 
            //if (ActiveTab == null) return;
 
            //bool someTabHitted = false;
 
            ////Check if mouse on tab
            //if (ActiveTab.TabContentBounds.Contains(e.X, e.Y))
            //{
            //    //Do nothing, everything is on the sensor
            //}
            ////Check if mouse on orb
            //else if (OrbVisible && OrbBounds.Contains(e.Location) && !OrbSelected)
            //{
            //    OrbSelected = true;
            //    Invalidate(OrbBounds);
            //}
            ////Check if mouse on QuickAccess toolbar
            //else if (QuickAcessToolbar.Visible && QuickAcessToolbar.Bounds.Contains(e.Location))
            //{
 
            //}
            //else
            //{
            //    //look for mouse on tabs
            //    foreach (RibbonTab tab in Tabs)
            //    {
            //        if (tab.TabBounds.Contains(e.X, e.Y))
            //        {
            //            SetSelectedTab(tab);
            //            someTabHitted = true;
            //            tab.OnMouseMove(e);
            //        }
            //    }
            //}
 
            //if (!someTabHitted)
            //    SetSelectedTab(null);
 
            ////Clear the orb highlight
            //if (OrbSelected && !OrbBounds.Contains(e.Location))
            //{
            //    OrbSelected = false;
            //    Invalidate(OrbBounds);
            //}
            #endregion
        }
 
        /// <summary>
        /// Overriden. Raises the MouseUp event and tunnels the message to child elements
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"></see> that contains the event data.</param>
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
        }
 
        /// <summary>
        /// Overriden. Raises the MouseDown event and tunnels the message to child elements
        /// </summary>
        protected override void OnMouseDown(MouseEventArgs e)
        {
            //Kevin Carbis - this fixes the focus problem with textboxes when a different item is clicked
            //and the edit box is still visible. This will now close the edit box for the textbox that previously
            //had the focus. Otherwise the first click on a button would close the textbox and you would have to click twice.
            //Control.Focus();
            if (ActiveTextBox != null)
                (ActiveTextBox as RibbonTextBox).EndEdit();
 
            base.OnMouseDown(e);
 
            if (OrbBounds.Contains(e.Location))
            {
                OrbMouseDown();
            }
            else
            {
                TabHitTest(e.X, e.Y);
            }
 
        }
 
        /// <summary>
        /// Handles the mouse wheel
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            base.OnMouseWheel(e);
 
            //if (Tabs.Count == 0 || ActiveTab == null) return;
 
            //int index = Tabs.IndexOf(ActiveTab);
 
            //if (e.Delta < 0)
            //{
            //   _tabSum += 0.4f;
            //}
            //else
            //{
            //   _tabSum -= 0.4f;
            //}
 
            //int tabRounded = Convert.ToInt16(Math.Round(_tabSum));
 
            //if (tabRounded != 0)
            //{
            //   index += tabRounded;
 
            //   if (index < 0)
            //   {
            //      index = 0;
            //   }
            //   else if (index >= Tabs.Count - 1)
            //   {
            //      index = Tabs.Count - 1;
            //   }
 
            //   ActiveTab = Tabs[index];
            //   _tabSum = 0f;
            //}
        }
 
        /// <summary>
        /// Handles the MouseMove on a RibbonHost control. Not the best solution, but there
        /// is no simple method to hook into the host controls.
        /// </summary>
        /// <param name="e"></param>
        internal void OnRibbonHostMouseMove(MouseEventArgs e)
        {
            OnMouseMove(e);
        }
 
        /// <summary>
        /// Overriden. Raises the OnSizeChanged event and performs layout calculations
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
        protected override void OnSizeChanged(EventArgs e)
        {
            UpdateRegions();
 
            RemoveHelperControls();
 
            base.OnSizeChanged(e);
        }
 
        /// <summary>
        /// Handles when its parent has changed
        /// </summary>
        /// <param name="e"></param>
        protected override void OnParentChanged(EventArgs e)
        {
            base.OnParentChanged(e);
 
            if (!(Site != null && Site.DesignMode))
            {
                BorderMode = BorderMode;
 
                if (Parent is IRibbonForm)
                {
                    FormHelper.Ribbon = this;
                }
            }
 
            if (Parent != null)
            {
                Control p = Parent;
                while (p.Parent != null)
                    p = p.Parent;
                Form parentForm = p as Form;
                if (parentForm != null)
                    parentForm.Deactivate += parentForm_Deactivate;
            }
        }
 
        private void parentForm_Deactivate(object sender, EventArgs e)
        {
            if (Form.ActiveForm == null)  // check for ActiveForm, because Click in Orb Menu causes the Form as well to fire the Deactivate Event
            {
                RibbonPopupManager.Dismiss(RibbonPopupManager.DismissReason.AppFocusChanged);
            }
        }
 
        private void OnPopupRegistered(object sender, EventArgs args)
        {
            if (RibbonPopupManager.PopupCount == 1)
                SetUpHooks();
        }
 
        private void OnPopupUnregistered(object sender, EventArgs args)
        {
            if (RibbonPopupManager.PopupCount == 0 && (Minimized == false || (Minimized && Expanded == false)))
                DisposeHooks();
        }
 
        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
 
            // Because the RibbonItem, RibbonPanel and RibbonTab return "Visible == false" if any of
            // their parents is not visible, a redraw is required when the Ribbon becomes visible finally!
            if (Visible)
            {
                UpdateRegions();
                Invalidate();
            }
        }
 
        #endregion
 
    }
}