-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPlaceholderTextBox.cs
367 lines (295 loc) · 12.4 KB
/
PlaceholderTextBox.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
using System.ComponentModel;
using System.Drawing;
namespace System.Windows.Forms
{
/// <summary>
/// Represents a Windows text box control with placeholder.
/// </summary>
public class PlaceholderTextBox : TextBox
{
#region Properties
string _placeholderText = DEFAULT_PLACEHOLDER;
bool _isPlaceholderActive = true;
/// <summary>
/// Gets a value indicating whether the Placeholder is active.
/// </summary>
[Browsable(false)]
public bool IsPlaceholderActive
{
get { return _isPlaceholderActive; }
private set
{
if (_isPlaceholderActive == value) return;
// Disable operating system handling for mouse events
// This prevents the user to select the placeholder with mouse or double clicking
SetStyle(ControlStyles.UserMouse, value);
// If text equals the placeholder and Reset is called, the actual text doesn't change but the IsPlaceholderActive does.
// Thus the style (Text or Placeholder) is not updated.
// Invalidate forces that
Invalidate();
_isPlaceholderActive = value;
OnPlaceholderActiveChanged(value);
}
}
/// <summary>
/// Gets or sets the placeholder in the PlaceholderTextBox.
/// </summary>
[Description("The placeholder associated with the control."), Category("Placeholder"), DefaultValue(DEFAULT_PLACEHOLDER)]
public string PlaceholderText
{
get { return _placeholderText; }
set
{
_placeholderText = value;
// Only use the new value if the placeholder is active.
if (IsPlaceholderActive)
Text = value;
}
}
/// <summary>
/// Gets or sets the current text in the TextBox.
/// </summary>
[Browsable(false)]
public override string Text
{
get
{
// Check 'base.Text == Placeholder' because in some cases IsPlaceholderActive changes too late although it isn't the placeholder anymore.
if (IsPlaceholderActive && base.Text == PlaceholderText)
return "";
return base.Text;
}
set { base.Text = value; }
}
Color _placeholderTextColor;
/// <summary>
/// Gets or sets the foreground color of the control.
/// </summary>
[Description("The foreground color of this component, which is used to display the placeholder."), Category("Appearance"), DefaultValue(typeof(Color), "InactiveCaption")]
public Color PlaceholderTextColor
{
get { return _placeholderTextColor; }
set
{
if (_placeholderTextColor == value) return;
_placeholderTextColor = value;
// Force redraw to show new color in designer instantly
if (DesignMode)
Invalidate();
}
}
/// <summary>
/// Gets or sets the foreground color of the control.
/// </summary>
[Description("The foreground color of this component, which is used to display text."), Category("Appearance"), DefaultValue(typeof(Color), "WindowText")]
public Color TextColor { get; set; }
/// <summary>
/// Do not access directly. Use TextColor.
/// </summary>
[Browsable(false)]
public override Color ForeColor
{
get
{
if (IsPlaceholderActive)
return PlaceholderTextColor;
return TextColor;
}
set { TextColor = value; }
}
/// <summary>
/// Gets the length of text in the control.
/// </summary>
public override int TextLength => IsPlaceholderActive ? 0 : base.TextLength;
/// <summary>
/// Occurs when the value of the IsPlaceholderActive property has changed.
/// </summary>
[Description("Occurs when the value of the IsPlaceholderInside property has changed.")]
public event EventHandler<PlaceholderActiveChangedEventArgs> PlaceholderActiveChanged;
#endregion
#region Global Variables
/// <summary>
/// Specifies the default placeholder text.
/// </summary>
const string DEFAULT_PLACEHOLDER = "<Input>";
// Doc: https://msdn.microsoft.com/en-us/library/windows/desktop/bb761661(v=vs.85).aspx
const int EM_SETSEL = 0x00B1;
/// <summary>
/// Flag to avoid the TextChanged Event. Don't access directly, use Method 'ActionWithoutTextChanged(Action act)' instead.
/// </summary>
bool avoidTextChanged;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the PlaceholderTextBox class.
/// </summary>
public PlaceholderTextBox()
{
// Through this line the default placeholder gets displayed in designer
base.Text = PlaceholderText;
TextColor = SystemColors.WindowText;
PlaceholderTextColor = SystemColors.InactiveCaption;
SetStyle(ControlStyles.UserMouse, true);
}
#endregion
#region Functions
/// <summary>
/// Inserts placeholder, assigns placeholder style and sets cursor to first position.
/// </summary>
public void Reset()
{
if (IsPlaceholderActive) return;
IsPlaceholderActive = true;
Text = PlaceholderText;
Select(0, 0);
}
/// <summary>
/// Run an action with avoiding the TextChanged event.
/// </summary>
/// <param name="act">Specifies the action to run.</param>
private void ActionWithoutTextChanged(Action act)
{
avoidTextChanged = true;
act.Invoke();
avoidTextChanged = false;
}
private void UpdateText()
{
// Run code with avoiding recursive call
ActionWithoutTextChanged(delegate
{
// If the Text is empty, insert placeholder and set cursor to the first position
if (!IsPlaceholderActive && String.IsNullOrEmpty(Text))
{
// Allow default length for the placeholder
// If we wouldn't do this, the placeholder will never disappear if
// PlaceholderText.Length > MaxLength because the user cannot type anything
MaxLength = 32767;
Reset();
}
// If the placeholder has been active but now the text changed,
// set the textbox to its usual state
else if (IsPlaceholderActive && Text.Length > 0)
{
MaxLength = customMaxLength;
IsPlaceholderActive = false;
// If you set Text programmatically it won't contain the PlaceholderText.
// Thus we do not have to remove it
// An issue is you cannot set a Text programmatically which has the structure [prefix][placeholder]
// Note the missing suffix because we use "EndsWith"
// Well, you can but the placeholder becomes removed, the prefix will be in the textbox
// The reason is we cannot distinguish if a user typed something or the Text has been set programmatically
if (Text.EndsWith(PlaceholderText))
{
Text = Text.Substring(0, TextLength - PlaceholderText.Length);
}
// If we copied something, trim it to the MaxLength
if (Text.Length > MaxLength)
Text = Text.Substring(0, MaxLength);
// Set selection to last position
Select(TextLength, 0);
}
});
}
#endregion
#region Events
int customMaxLength;
protected override void OnCreateControl()
{
base.OnCreateControl();
// Save the user specified MaxLength
customMaxLength = MaxLength;
// Set to default for the placeholder
MaxLength = 32767;
}
protected override void OnTextChanged(EventArgs e)
{
// Check flag
if (avoidTextChanged) return;
UpdateText();
base.OnTextChanged(e);
}
protected override void WndProc(ref Message m)
{
// Prevent selection through Windows default controls. ("Select all" in context menu)
if (IsPlaceholderActive && m.Msg == EM_SETSEL) return;
base.WndProc(ref m);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (IsPlaceholderActive)
{
// Prevents navigating through the placeholder with navigation keys and placeholder is not deletable with delete key
if (e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Up ||
e.KeyCode == Keys.Down ||
e.KeyCode == Keys.Delete ||
e.KeyCode == Keys.Home ||
e.KeyCode == Keys.End ||
e.KeyCode == Keys.Back)
{
e.SuppressKeyPress = true;
}
// Prevent selecting the placeholder text
if (e.KeyCode == Keys.A && e.Modifiers.HasFlag(Keys.Control))
{
e.SuppressKeyPress = true;
}
}
base.OnKeyDown(e);
}
protected virtual void OnPlaceholderActiveChanged(bool newValue)
{
PlaceholderActiveChanged?.Invoke(this, new PlaceholderActiveChangedEventArgs(newValue));
}
#endregion
#region Avoid full text selection after first display with TabIndex = 0
// Base class has a selectionSet property, but it is private.
// We need to shadow with our own variable. If true, this means
// "don't mess with the selection, the user did it."
bool selectionSet;
protected override void OnGotFocus(EventArgs e)
{
bool needToDeselect = false;
// We don't want to avoid calling the base implementation
// completely. We mirror the logic that we are trying to avoid;
// if the base implementation will select all of the text, we
// set a boolean.
if (!selectionSet)
{
selectionSet = true;
if (SelectionLength == 0 && MouseButtons == MouseButtons.None)
{
needToDeselect = true;
}
}
// Call the base implementation
base.OnGotFocus(e);
// Did we notice that the text was selected automatically? Let's
// de-select it and put the caret at the end.
if (!needToDeselect) return;
SelectionStart = 0;
DeselectAll();
}
#endregion
}
/// <summary>
/// Provides data for the PlaceholderActiveChanged event.
/// </summary>
public class PlaceholderActiveChangedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the PlaceholderActiveChangedEventArgs class.
/// </summary>
/// <param name="isActive">Specifies whether the placeholder is currently active.</param>
public PlaceholderActiveChangedEventArgs(bool isActive)
{
IsActive = isActive;
}
/// <summary>
/// Gets the new value of the IsPlaceholderActive property.
/// </summary>
public bool IsActive { get; private set; }
}
}