Menu

[38707f]: / TextBoxEx.cs  Maximize  Restore  History

Download this file

98 lines (86 with data), 3.5 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
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
namespace GitForce
{
/// <summary>
/// This is a fancy text box which is used by the direct command line box.
///
/// The callback it implements, TextReady(), will trigger when the user
/// presses Enter in the box. It will be called only when there is a non-empty
/// text in the box (user does not have to check for empty text.)
/// Also, text will be trimmed at the front and back from extra spaces.
///
/// The text box will clear itself after the TextReady() has been sent.
/// </summary>
public class TextBoxEx : TextBox
{
public delegate void TextReadyEventHandler(object sender, string text);
// Declare an event to trigger on Enter key
[Category("Action")]
[Description("Occurs when the text is ready for consumption")]
public event TextReadyEventHandler TextReady;
// List of strings entered so far to hold the history of input
// Each string is unique
private readonly List<string> history = new List<string>();
// Index into history when browsing it (Up / Down)
private int iH;
// Handler called on every key press into the subclassed TextBox
// Using this handler we capture cursor up and down keys
protected override void OnKeyDown(KeyEventArgs e)
{
switch (e.KeyCode)
{
// Up suggests a history entry
case Keys.Up:
if (iH > 0)
{
iH--;
Text = history[iH];
Select(Text.Length, 0);
}
e.Handled = true;
break;
// Down suggests a history entry
case Keys.Down:
if (iH < history.Count-1)
{
iH++;
Text = history[iH];
Select(Text.Length, 0);
}
e.Handled = true;
break;
}
base.OnKeyDown(e);
}
// Handler called on every key press into the subclassed TextBox
// Using this handler we capture ASCII keys
protected override void OnKeyPress(KeyPressEventArgs e)
{
switch (e.KeyChar)
{
// On Enter, process the buffer and send a method
case (char)Keys.Enter:
// Trim the line from the extra spaces at both ends
Text = Text.Trim();
// Send a message that the text is ready (if there is any text available)
if (TextReady != null && Text.Length > 0)
TextReady(this, Text);
if (Text.Length > 0 && !history.Contains(Text))
history.Add(Text);
iH = history.Count();
Text = string.Empty;
e.Handled = true;
break;
// ESC clears the text box entry
case (char)Keys.Escape:
Text = string.Empty;
e.Handled = true; // This also avoids the chime
break;
}
base.OnKeyPress(e);
}
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.