-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathControl.cs
More file actions
13596 lines (11926 loc) · 469 KB
/
Control.cs
File metadata and controls
13596 lines (11926 loc) · 469 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Drawing;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Windows.Forms.Automation;
using System.Windows.Forms.Layout;
using System.Windows.Forms.Primitives;
using Microsoft.Win32;
using Windows.Win32.System.Ole;
using Windows.Win32.UI.Input.KeyboardAndMouse;
using static Interop;
using ComTypes = System.Runtime.InteropServices.ComTypes;
using Encoding = System.Text.Encoding;
namespace System.Windows.Forms;
/// <summary>
/// Defines the base class for controls, which are components with visual representation.
/// </summary>
/// <remarks>
/// <para>
/// Do not add instance variables to Control absolutely necessary. Every control on a form has the overhead of
/// all of these variables.
/// </para>
/// </remarks>
[DefaultProperty(nameof(Text))]
[DefaultEvent(nameof(Click))]
[Designer($"System.Windows.Forms.Design.ControlDesigner, {AssemblyRef.SystemDesign}")]
[DesignerSerializer(
$"System.Windows.Forms.Design.ControlCodeDomSerializer, {AssemblyRef.SystemDesign}",
$"System.ComponentModel.Design.Serialization.CodeDomSerializer, {AssemblyRef.SystemDesign}")]
[ToolboxItemFilter("System.Windows.Forms")]
public unsafe partial class Control :
Component,
ISupportOleDropSource,
IDropTarget,
ISynchronizeInvoke,
IWin32Window,
IArrangedElement,
IBindableComponent,
IKeyboardToolTip,
IHandle<HWND>
{
#if DEBUG
internal static readonly TraceSwitch s_paletteTracing = new(
"PaletteTracing",
"Debug Palette code");
internal static readonly TraceSwitch s_controlKeyboardRouting = new(
"ControlKeyboardRouting",
"Debug Keyboard routing for controls");
private protected static readonly TraceSwitch s_focusTracing = new(
"FocusTracing",
"Debug focus/active control/enter/leave");
private static readonly BooleanSwitch s_assertOnControlCreateSwitch = new(
"AssertOnControlCreate",
"Assert when anything directly deriving from control is created.");
private protected static readonly BooleanSwitch s_traceMnemonicProcessing = new(
"TraceCanProcessMnemonic",
"Trace mnemonic processing calls to assure right child-parent call ordering.");
private protected void TraceCanProcessMnemonic()
{
if (s_traceMnemonicProcessing.Enabled)
{
string str;
try
{
str = $"{GetType().Name}<{Text}>";
int maxFrameCount = new StackTrace().FrameCount;
if (maxFrameCount > 5)
{
maxFrameCount = 5;
}
int frameIndex = 1;
while (frameIndex < maxFrameCount)
{
StackFrame sf = new StackFrame(frameIndex);
if (frameIndex == 2 && sf.GetMethod()!.Name.Equals("CanProcessMnemonic"))
{
// log immediate call if in a virtual/recursive call.
break;
}
str += new StackTrace(sf).ToString().TrimEnd();
frameIndex++;
}
if (frameIndex > 2)
{
// new CanProcessMnemonic virtual/recursive call stack.
str = "\r\n" + str;
}
}
catch (Exception ex)
{
str = ex.ToString();
}
Debug.WriteLine(str);
}
}
#else
internal static readonly TraceSwitch? s_paletteTracing;
internal static readonly TraceSwitch? s_controlKeyboardRouting;
private protected readonly TraceSwitch? s_focusTracing;
#endif
#if DEBUG
private static readonly BooleanSwitch s_bufferPinkRect = new(
"BufferPinkRect",
"Renders a pink rectangle with painting double buffered controls");
private static readonly BooleanSwitch s_bufferDisabled = new(
"BufferDisabled",
"Makes double buffered controls non-double buffered");
#endif
private static readonly uint WM_GETCONTROLNAME = PInvoke.RegisterWindowMessage("WM_GETCONTROLNAME");
private static readonly uint WM_GETCONTROLTYPE = PInvoke.RegisterWindowMessage("WM_GETCONTROLTYPE");
private static readonly object s_autoSizeChangedEvent = new();
private static readonly object s_keyDownEvent = new();
private static readonly object s_keyPressEvent = new();
private static readonly object s_keyUpEvent = new();
private static readonly object s_mouseDownEvent = new();
private static readonly object s_mouseEnterEvent = new();
private static readonly object s_mouseLeaveEvent = new();
private static readonly object s_dpiChangedBeforeParentEvent = new();
private static readonly object s_dpiChangedAfterParentEvent = new();
private static readonly object s_mouseHoverEvent = new();
private static readonly object s_mouseMoveEvent = new();
private static readonly object s_mouseUpEvent = new();
private static readonly object s_mouseWheelEvent = new();
private static readonly object s_clickEvent = new();
private static readonly object s_clientSizeEvent = new();
private static readonly object s_doubleClickEvent = new();
private static readonly object s_mouseClickEvent = new();
private static readonly object s_mouseDoubleClickEvent = new();
private static readonly object s_mouseCaptureChangedEvent = new();
private static readonly object s_moveEvent = new();
private static readonly object s_resizeEvent = new();
private static readonly object s_layoutEvent = new();
private static readonly object s_gotFocusEvent = new();
private static readonly object s_lostFocusEvent = new();
private static readonly object s_enterEvent = new();
private static readonly object s_leaveEvent = new();
private static readonly object s_handleCreatedEvent = new();
private static readonly object s_handleDestroyedEvent = new();
private static readonly object s_controlAddedEvent = new();
private static readonly object s_controlRemovedEvent = new();
private static readonly object s_changeUICuesEvent = new();
private static readonly object s_systemColorsChangedEvent = new();
private static readonly object s_validatingEvent = new();
private static readonly object s_validatedEvent = new();
private static readonly object s_styleChangedEvent = new();
private static readonly object s_imeModeChangedEvent = new();
private static readonly object s_helpRequestedEvent = new();
private static readonly object s_paintEvent = new();
private static readonly object s_invalidatedEvent = new();
private static readonly object s_queryContinueDragEvent = new();
private static readonly object s_giveFeedbackEvent = new();
private static readonly object s_dragEnterEvent = new();
private static readonly object s_dragLeaveEvent = new();
private static readonly object s_dragOverEvent = new();
private static readonly object s_dragDropEvent = new();
private static readonly object s_queryAccessibilityHelpEvent = new();
private static readonly object s_backgroundImageEvent = new();
private static readonly object s_backgroundImageLayoutEvent = new();
private static readonly object s_bindingContextEvent = new();
private static readonly object s_backColorEvent = new();
private static readonly object s_parentEvent = new();
private static readonly object s_visibleEvent = new();
private static readonly object s_textEvent = new();
private static readonly object s_tabStopEvent = new();
private static readonly object s_tabIndexEvent = new();
private static readonly object s_sizeEvent = new();
private static readonly object s_rightToLeftEvent = new();
private static readonly object s_locationEvent = new();
private static readonly object s_foreColorEvent = new();
private static readonly object s_fontEvent = new();
private static readonly object s_enabledEvent = new();
private static readonly object s_dockEvent = new();
private static readonly object s_cursorEvent = new();
private static readonly object s_contextMenuStripEvent = new();
private static readonly object s_causesValidationEvent = new();
private static readonly object s_regionChangedEvent = new();
private static readonly object s_marginChangedEvent = new();
private protected static readonly object s_paddingChangedEvent = new();
private static readonly object s_previewKeyDownEvent = new();
private static readonly object s_dataContextEvent = new();
private static MessageId s_threadCallbackMessage;
private static ContextCallback? s_invokeMarshaledCallbackHelperDelegate;
#pragma warning disable IDE1006 // Naming Styles
[ThreadStatic]
private static bool t_inCrossThreadSafeCall;
[ThreadStatic]
internal static HelpInfo? t_currentHelpInfo;
#pragma warning restore IDE1006
private static FontHandleWrapper? s_defaultFontHandleWrapper;
private const short PaintLayerBackground = 1;
private const short PaintLayerForeground = 2;
private const byte RequiredScalingEnabledMask = 0x10;
private const byte RequiredScalingMask = 0x0F;
private const byte HighOrderBitMask = 0x80;
private static Font? s_defaultFont;
// Property store keys for properties. The property store allocates most efficiently
// in groups of four, so we try to lump properties in groups of four based on how
// likely they are going to be used in a group.
private static readonly int s_namePropertyProperty = PropertyStore.CreateKey();
private static readonly int s_backBrushProperty = PropertyStore.CreateKey();
private static readonly int s_fontHeightProperty = PropertyStore.CreateKey();
private static readonly int s_currentAmbientFontProperty = PropertyStore.CreateKey();
private static readonly int s_controlsCollectionProperty = PropertyStore.CreateKey();
private static readonly int s_backColorProperty = PropertyStore.CreateKey();
private static readonly int s_foreColorProperty = PropertyStore.CreateKey();
internal static readonly int s_fontProperty = PropertyStore.CreateKey();
private static readonly int s_backgroundImageProperty = PropertyStore.CreateKey();
private static readonly int s_fontHandleWrapperProperty = PropertyStore.CreateKey();
private static readonly int s_userDataProperty = PropertyStore.CreateKey();
private static readonly int s_cursorProperty = PropertyStore.CreateKey();
private static readonly int s_regionProperty = PropertyStore.CreateKey();
private static readonly int s_rightToLeftProperty = PropertyStore.CreateKey();
private static readonly int s_bindingsProperty = PropertyStore.CreateKey();
private static readonly int s_bindingManagerProperty = PropertyStore.CreateKey();
private static readonly int s_accessibleDefaultActionProperty = PropertyStore.CreateKey();
private static readonly int s_accessibleDescriptionProperty = PropertyStore.CreateKey();
private static readonly int s_accessibilityProperty = PropertyStore.CreateKey();
private static readonly int s_ncAccessibilityProperty = PropertyStore.CreateKey();
private static readonly int s_accessibleNameProperty = PropertyStore.CreateKey();
private static readonly int s_accessibleRoleProperty = PropertyStore.CreateKey();
private static readonly int s_activeXImplProperty = PropertyStore.CreateKey();
private static readonly int s_controlVersionInfoProperty = PropertyStore.CreateKey();
private static readonly int s_backgroundImageLayoutProperty = PropertyStore.CreateKey();
private static readonly int s_contextMenuStripProperty = PropertyStore.CreateKey();
private static readonly int s_autoScrollOffsetProperty = PropertyStore.CreateKey();
private static readonly int s_useCompatibleTextRenderingProperty = PropertyStore.CreateKey();
private static readonly int s_imeWmCharsToIgnoreProperty = PropertyStore.CreateKey();
private static readonly int s_imeModeProperty = PropertyStore.CreateKey();
private static readonly int s_disableImeModeChangedCountProperty = PropertyStore.CreateKey();
private static readonly int s_lastCanEnableImeProperty = PropertyStore.CreateKey();
private static readonly int s_cacheTextCountProperty = PropertyStore.CreateKey();
private static readonly int s_acheTextFieldProperty = PropertyStore.CreateKey();
private static readonly int s_ambientPropertiesServiceProperty = PropertyStore.CreateKey();
private static readonly int s_dataContextProperty = PropertyStore.CreateKey();
private static bool s_needToLoadComCtl = true;
// This switch determines the default text rendering engine to use by some controls that support switching rendering engine.
// CheckedListBox, PropertyGrid, GroupBox, Label and LinkLabel, and ButtonBase controls.
// True means use GDI+, false means use GDI (TextRenderer).
internal static bool UseCompatibleTextRenderingDefault { get; set; } = true;
// Control instance members
//
// Note: Do not add anything to this list unless absolutely necessary.
// Every control on a form has the overhead of all of these
// variables!
// Resist the temptation to make this variable 'internal' rather than
// private. Handle access should be tightly controlled, and is in this
// file. Making it 'internal' makes controlling it quite difficult.
private readonly ControlNativeWindow _window;
private Control? _parent;
private WeakReference<Control>? _reflectParent;
private CreateParams? _createParams;
private int _x;
private int _y;
private int _width;
private int _height;
private int _clientWidth;
private int _clientHeight;
private States _state;
private ExtendedStates _extendedState;
/// <summary>
/// User supplied control style
/// </summary>
private ControlStyles _controlStyle;
private int _tabIndex;
private string? _text; // See ControlStyles.CacheText for usage notes
private byte _requiredScaling; // bits 0-4: BoundsSpecified stored in RequiredScaling property. Bit 5: RequiredScalingEnabled property.
private TRACKMOUSEEVENT _trackMouseEvent;
private short _updateCount;
private LayoutEventArgs? _cachedLayoutEventArgs;
private Queue<ThreadMethodEntry>? _threadCallbackList;
internal int _deviceDpi;
internal int _oldDeviceDpi;
// For keeping track of our ui state for focus and keyboard cues. Using a member
// variable here because we hit this a lot
private UICuesStates _uiCuesState;
// Stores scaled font from Dpi changed values. This is required to distinguish the Font change from
// Dpi changed events and explicit Font change/assignment.
private Font? _scaledControlFont;
private FontHandleWrapper? _scaledFontWrapper;
// ContainerControls like 'PropertyGrid' scale their children when they resize.
// no explicit scaling of children required in such cases. They have specific logic.
internal bool _doNotScaleChildren;
// Contains a collection of calculated fonts for various Dpi values of the control in the PerMonV2 mode.
private Dictionary<int, Font>? _dpiFonts;
// Flag to signify whether any child controls necessitate the calculation of AnchorsInfo, particularly in cases involving nested containers.
internal bool _childControlsNeedAnchorLayout;
// Inform whether the AnchorsInfo needs to be reevaluated, especially when the control's bounds have been altered explicitly.
internal bool _forceAnchorCalculations;
internal byte LayoutSuspendCount { get; private set; }
#if DEBUG
internal void AssertLayoutSuspendCount(int value)
{
Debug.Assert(value == LayoutSuspendCount, "Suspend/Resume layout mismatch!");
}
/*
example usage
#if DEBUG
int dbgLayoutCheck = LayoutSuspendCount;
#endif
#if DEBUG
AssertLayoutSuspendCount(dbgLayoutCheck);
#endif
*/
#endif
/// <summary>
/// Initializes a new instance of the <see cref="Control"/> class.
/// </summary>
public Control() : this(true)
{
}
internal Control(bool autoInstallSyncContext) : base()
{
#if DEBUG
if (s_assertOnControlCreateSwitch.Enabled)
{
Debug.Assert(GetType().BaseType != typeof(Control), $"Direct derivative of Control Created: {GetType().FullName}");
Debug.Assert(GetType() != typeof(Control), "Control Created!");
}
#endif
Properties = new PropertyStore();
// Initialize Dpi to the value on the primary screen, we will have the correct value when the Handle is created.
_deviceDpi = _oldDeviceDpi = DpiHelper.DeviceDpi;
_window = new ControlNativeWindow(this);
RequiredScalingEnabled = true;
RequiredScaling = BoundsSpecified.All;
_tabIndex = -1;
_state = States.Visible | States.Enabled | States.TabStop | States.CausesValidation;
_extendedState = ExtendedStates.InterestedInUserPreferenceChanged;
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.StandardClick |
ControlStyles.StandardDoubleClick |
ControlStyles.UseTextForAccessibility |
ControlStyles.Selectable, true);
// We baked the "default default" margin and min size into CommonProperties
// so that in the common case the PropertyStore would be empty. If, however,
// someone overrides these Default* methods, we need to write the default
// value into the PropertyStore in the ctor.
if (DefaultMargin != CommonProperties.DefaultMargin)
{
Margin = DefaultMargin;
}
if (DefaultMinimumSize != CommonProperties.DefaultMinimumSize)
{
MinimumSize = DefaultMinimumSize;
}
if (DefaultMaximumSize != CommonProperties.DefaultMaximumSize)
{
MaximumSize = DefaultMaximumSize;
}
// Compute our default size.
Size defaultSize = DefaultSize;
_width = defaultSize.Width;
_height = defaultSize.Height;
// DefaultSize may have hit GetPreferredSize causing a PreferredSize to be cached. The
// PreferredSize may change as a result of the current size. Since a SetBoundsCore did
// not happen, so we need to clear the preferredSize cache manually.
CommonProperties.xClearPreferredSizeCache(this);
if (_width != 0 && _height != 0)
{
RECT rect = default;
CreateParams cp = CreateParams;
AdjustWindowRectExForControlDpi(ref rect, (WINDOW_STYLE)cp.Style, false, (WINDOW_EX_STYLE)cp.ExStyle);
_clientWidth = _width - rect.Width;
_clientHeight = _height - rect.Height;
}
// Set up for async operations on this thread.
if (autoInstallSyncContext)
{
WindowsFormsSynchronizationContext.InstallIfNeeded();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Control"/> class.
/// </summary>
public Control(string? text) : this(null, text)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Control"/> class.
/// </summary>
public Control(string? text, int left, int top, int width, int height) : this(null, text, left, top, width, height)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Control"/> class.
/// </summary>
public Control(Control? parent, string? text) : this()
{
Parent = parent;
Text = text;
}
/// <summary>
/// Initializes a new instance of the <see cref="Control"/> class.
/// </summary>
public Control(Control? parent, string? text, int left, int top, int width, int height) : this(parent, text)
{
Location = new Point(left, top);
Size = new Size(width, height);
}
/// <summary>
/// Gets control Dpi awareness context value.
/// </summary>
internal DPI_AWARENESS_CONTEXT DpiAwarenessContext => _window.DpiAwarenessContext;
/// <summary>
/// The Accessibility Object for this Control
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[SRDescription(nameof(SR.ControlAccessibilityObjectDescr))]
public AccessibleObject AccessibilityObject
{
get
{
AccessibleObject? accessibleObject = (AccessibleObject?)Properties.GetObject(s_accessibilityProperty);
if (accessibleObject is null)
{
accessibleObject = CreateAccessibilityInstance();
Properties.SetObject(s_accessibilityProperty, accessibleObject);
}
Debug.Assert(accessibleObject is not null, "Failed to create accessibility object");
return accessibleObject;
}
}
/// <summary>
/// Private accessibility object for control, used to wrap the object that
/// OLEACC.DLL creates to represent the control's non-client (NC) region.
/// </summary>
private AccessibleObject NcAccessibilityObject
{
get
{
AccessibleObject? ncAccessibleObject = (AccessibleObject?)Properties.GetObject(s_ncAccessibilityProperty);
if (ncAccessibleObject is null)
{
ncAccessibleObject = new ControlAccessibleObject(this, (int)OBJECT_IDENTIFIER.OBJID_WINDOW);
Properties.SetObject(s_ncAccessibilityProperty, ncAccessibleObject);
}
Debug.Assert(ncAccessibleObject is not null, "Failed to create NON-CLIENT accessibility object");
return ncAccessibleObject;
}
}
/// <summary>
/// Returns a specific AccessibleObject associated with this
/// control, based on standard "accessible object id".
/// </summary>
private AccessibleObject? GetAccessibilityObject(int accObjId)
{
AccessibleObject? accessibleObject;
switch ((OBJECT_IDENTIFIER)accObjId)
{
case OBJECT_IDENTIFIER.OBJID_CLIENT:
accessibleObject = AccessibilityObject;
break;
case OBJECT_IDENTIFIER.OBJID_WINDOW:
accessibleObject = NcAccessibilityObject;
break;
default:
if (accObjId > 0)
{
accessibleObject = GetAccessibilityObjectById(accObjId);
}
else
{
accessibleObject = null;
}
break;
}
return accessibleObject;
}
/// <summary>
/// Returns a specific AccessibleObject associated w/ the objectID
/// </summary>
protected virtual AccessibleObject? GetAccessibilityObjectById(int objectId)
{
if (this is IAutomationLiveRegion)
{
return AccessibilityObject;
}
return null;
}
/// <summary>
/// The default action description of the control
/// </summary>
[SRCategory(nameof(SR.CatAccessibility))]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[SRDescription(nameof(SR.ControlAccessibleDefaultActionDescr))]
public string? AccessibleDefaultActionDescription
{
get => (string?)Properties.GetObject(s_accessibleDefaultActionProperty);
set => Properties.SetObject(s_accessibleDefaultActionProperty, value);
}
/// <summary>
/// The accessible description of the control
/// </summary>
[SRCategory(nameof(SR.CatAccessibility))]
[DefaultValue(null)]
[Localizable(true)]
[SRDescription(nameof(SR.ControlAccessibleDescriptionDescr))]
public string? AccessibleDescription
{
get => (string?)Properties.GetObject(s_accessibleDescriptionProperty);
set => Properties.SetObject(s_accessibleDescriptionProperty, value);
}
/// <summary>
/// The accessible name of the control
/// </summary>
[SRCategory(nameof(SR.CatAccessibility))]
[DefaultValue(null)]
[Localizable(true)]
[SRDescription(nameof(SR.ControlAccessibleNameDescr))]
public string? AccessibleName
{
get => (string?)Properties.GetObject(s_accessibleNameProperty);
set => Properties.SetObject(s_accessibleNameProperty, value);
}
/// <summary>
/// The accessible role of the control
/// </summary>
[SRCategory(nameof(SR.CatAccessibility))]
[DefaultValue(AccessibleRole.Default)]
[SRDescription(nameof(SR.ControlAccessibleRoleDescr))]
public AccessibleRole AccessibleRole
{
get
{
int role = Properties.GetInteger(s_accessibleRoleProperty, out bool found);
if (found)
{
return (AccessibleRole)role;
}
else
{
return AccessibleRole.Default;
}
}
set
{
//valid values are -1 to 0x40
SourceGenerated.EnumValidator.Validate(value);
Properties.SetInteger(s_accessibleRoleProperty, (int)value);
}
}
/// <summary>
/// The AllowDrop property. If AllowDrop is set to true then
/// this control will allow drag and drop operations and events to be used.
/// </summary>
[SRCategory(nameof(SR.CatBehavior))]
[DefaultValue(false)]
[SRDescription(nameof(SR.ControlAllowDropDescr))]
public virtual bool AllowDrop
{
get
{
return GetState(States.AllowDrop);
}
set
{
if (GetState(States.AllowDrop) != value)
{
SetState(States.AllowDrop, value);
if (IsHandleCreated)
{
try
{
SetAcceptDrops(value);
}
catch
{
// If there is an error, back out the AllowDrop state...
//
SetState(States.AllowDrop, !value);
throw;
}
}
}
}
}
// Queries the Site for AmbientProperties. May return null.
// Do not confuse with inheritedProperties -- the service is turned to
// after we've exhausted inheritedProperties.
private AmbientProperties? AmbientPropertiesService
{
get
{
AmbientProperties? props = (AmbientProperties?)Properties.GetObject(s_ambientPropertiesServiceProperty, out bool contains);
if (!contains)
{
if (Site is not null)
{
props = Site.GetService(typeof(AmbientProperties)) as AmbientProperties;
}
else
{
props = (AmbientProperties?)GetService(typeof(AmbientProperties));
}
if (props is not null)
{
Properties.SetObject(s_ambientPropertiesServiceProperty, props);
}
}
return props;
}
}
/// <summary>
/// The current value of the anchor property. The anchor property
/// determines which edges of the control are anchored to the container's
/// edges.
/// </summary>
[SRCategory(nameof(SR.CatLayout))]
[Localizable(true)]
[DefaultValue(CommonProperties.DefaultAnchor)]
[SRDescription(nameof(SR.ControlAnchorDescr))]
[RefreshProperties(RefreshProperties.Repaint)]
public virtual AnchorStyles Anchor
{
get => DefaultLayout.GetAnchor(this);
set => DefaultLayout.SetAnchor(this, value);
}
[SRCategory(nameof(SR.CatLayout))]
[RefreshProperties(RefreshProperties.All)]
[Localizable(true)]
[DefaultValue(CommonProperties.DefaultAutoSize)]
[SRDescription(nameof(SR.ControlAutoSizeDescr))]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual bool AutoSize
{
get { return CommonProperties.GetAutoSize(this); }
set
{
if (value != AutoSize)
{
CommonProperties.SetAutoSize(this, value);
if (ParentInternal is not null)
{
// DefaultLayout does not keep anchor information until it needs to. When
// AutoSize became a common property, we could no longer blindly call into
// DefaultLayout, so now we do a special InitLayout just for DefaultLayout.
if (value && ParentInternal.LayoutEngine == DefaultLayout.Instance)
{
ParentInternal.LayoutEngine.InitLayout(this, BoundsSpecified.Size);
}
LayoutTransaction.DoLayout(ParentInternal, this, PropertyNames.AutoSize);
}
OnAutoSizeChanged(EventArgs.Empty);
}
}
}
[SRCategory(nameof(SR.CatPropertyChanged))]
[SRDescription(nameof(SR.ControlOnAutoSizeChangedDescr))]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public event EventHandler? AutoSizeChanged
{
add => Events.AddHandler(s_autoSizeChangedEvent, value);
remove => Events.RemoveHandler(s_autoSizeChangedEvent, value);
}
/// <summary>
/// Controls the location of where this control is scrolled to in ScrollableControl.ScrollControlIntoView.
/// Default is the upper left hand corner of the control.
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
[DefaultValue(typeof(Point), "0, 0")]
public virtual Point AutoScrollOffset
{
get => Properties.TryGetObject(s_autoScrollOffsetProperty, out Point point)
? point
: Point.Empty;
set
{
if (AutoScrollOffset != value)
{
Properties.SetObject(s_autoScrollOffsetProperty, value);
}
}
}
protected void SetAutoSizeMode(AutoSizeMode mode) => CommonProperties.SetAutoSizeMode(this, mode);
protected AutoSizeMode GetAutoSizeMode() => CommonProperties.GetAutoSizeMode(this);
// Public because this is interesting for ControlDesigners.
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public virtual LayoutEngine LayoutEngine => DefaultLayout.Instance;
/// <summary>
/// The GDI brush for our background color.
/// Whidbey Note: Made this internal, since we need to use this in ButtonStandardAdapter. Also, renamed
/// from BackBrush to BackColorBrush due to a naming conflict with DataGrid's BackBrush.
/// </summary>
internal HBRUSH BackColorBrush
{
get
{
object? customBackBrush = Properties.GetObject(s_backBrushProperty);
if (customBackBrush is not null)
{
// We already have a valid brush. Unbox, and return.
return (HBRUSH)customBackBrush;
}
if (!Properties.ContainsObject(s_backColorProperty))
{
// No custom back color. See if we can get to our parent.
// The color check here is to account for parents and children who
// override the BackColor property.
if (_parent is not null && _parent.BackColor == BackColor)
{
return _parent.BackColorBrush;
}
}
// No parent, or we have a custom back color. Either way, we need to
// create our own.
Color color = BackColor;
HBRUSH backBrush;
if (color.IsSystemColor)
{
backBrush = PInvoke.GetSysColorBrush(color);
SetState(States.OwnCtlBrush, false);
}
else
{
backBrush = PInvoke.CreateSolidBrush((COLORREF)(uint)ColorTranslator.ToWin32(color));
SetState(States.OwnCtlBrush, true);
}
Debug.Assert(!backBrush.IsNull, "Failed to create brushHandle");
Properties.SetObject(s_backBrushProperty, backBrush);
return backBrush;
}
}
/// <summary>
/// Gets or sets the data context for the purpose of data binding.
/// This is an ambient property.
/// </summary>
/// <remarks>
/// Data context is a concept that allows elements to inherit information from their parent elements
/// about the data source that is used for binding. It's the duty of deriving controls which inherit from
/// this class to handle the provided data source accordingly. For example, UserControls, which use
/// <see cref="BindingSource"/> components for data binding scenarios could either handle the
/// <see cref="DataContextChanged"/> event or override <see cref="OnDataContextChanged(EventArgs)"/> to provide
/// the relevant data from the data context to a BindingSource component's <see cref="BindingSource.DataSource"/>.
/// </remarks>
[SRCategory(nameof(SR.CatData))]
[Browsable(false)]
[Bindable(true)]
public virtual object? DataContext
{
get => Properties.TryGetObject(s_dataContextProperty, out object? value)
? value
: ParentInternal?.DataContext;
set
{
if (Equals(value, DataContext))
{
return;
}
// When DataContext was different than its parent before, but now it is about to become the same,
// we're removing it altogether, so it can inherit the value from its parent.
if (Properties.ContainsObject(s_dataContextProperty) && Equals(ParentInternal?.DataContext, value))
{
Properties.RemoveObject(s_dataContextProperty);
OnDataContextChanged(EventArgs.Empty);
return;
}
Properties.SetObject(s_dataContextProperty, value);
OnDataContextChanged(EventArgs.Empty);
}
}
private bool ShouldSerializeDataContext()
=> Properties.ContainsObject(s_dataContextProperty);
private void ResetDataContext()
=> Properties.RemoveObject(s_dataContextProperty);
/// <summary>
/// The background color of this control. This is an ambient property and
/// will always return a non-null value.
/// </summary>
[SRCategory(nameof(SR.CatAppearance))]
[DispId(PInvoke.DISPID_BACKCOLOR)]
[SRDescription(nameof(SR.ControlBackColorDescr))]
public virtual Color BackColor
{
get
{
Color c = RawBackColor; // inheritedProperties.BackColor
if (!c.IsEmpty)
{
return c;
}
Control? parent = ParentInternal;
if (parent is not null && parent.CanAccessProperties)
{
c = parent.BackColor;
if (IsValidBackColor(c))
{
return c;
}
}
if (IsActiveX)
{
c = ActiveXAmbientBackColor;
}
if (c.IsEmpty)
{
AmbientProperties? ambient = AmbientPropertiesService;
if (ambient is not null)
{
c = ambient.BackColor;
}
}
if (!c.IsEmpty && IsValidBackColor(c))
{
return c;
}
else
{
return DefaultBackColor;
}
}
set
{
if (!value.Equals(Color.Empty) && !GetStyle(ControlStyles.SupportsTransparentBackColor) && value.A < 255)
{
throw new ArgumentException(SR.TransparentBackColorNotAllowed);
}
Color c = BackColor;
if (!value.IsEmpty || Properties.ContainsObject(s_backColorProperty))
{
Properties.SetColor(s_backColorProperty, value);
}
if (!c.Equals(BackColor))
{
OnBackColorChanged(EventArgs.Empty);
}
}
}
[SRCategory(nameof(SR.CatPropertyChanged))]
[SRDescription(nameof(SR.ControlOnBackColorChangedDescr))]
public event EventHandler? BackColorChanged
{
add => Events.AddHandler(s_backColorEvent, value);
remove => Events.RemoveHandler(s_backColorEvent, value);
}
/// <summary>
/// The background image of the control.
/// </summary>
[SRCategory(nameof(SR.CatAppearance))]
[DefaultValue(null)]
[Localizable(true)]
[SRDescription(nameof(SR.ControlBackgroundImageDescr))]
public virtual Image? BackgroundImage
{
get
{
return (Image?)Properties.GetObject(s_backgroundImageProperty);
}
set
{
if (BackgroundImage != value)
{
Properties.SetObject(s_backgroundImageProperty, value);
OnBackgroundImageChanged(EventArgs.Empty);
}
}
}
[SRCategory(nameof(SR.CatPropertyChanged))]
[SRDescription(nameof(SR.ControlOnBackgroundImageChangedDescr))]
public event EventHandler? BackgroundImageChanged
{
add => Events.AddHandler(s_backgroundImageEvent, value);
remove => Events.RemoveHandler(s_backgroundImageEvent, value);
}
/// <summary>
/// The BackgroundImageLayout of the control.
/// </summary>
[SRCategory(nameof(SR.CatAppearance))]
[DefaultValue(ImageLayout.Tile)]