|
|
|
 |
 |
Исходник |
 |
|
 |
 |
|
Автор:
|
|
|
Название:
|
RegexTextBox: TextBox с маской по регулярному выражению |
|
Дата:
|
02 November 2003 |
|
Описание: |
Думаю, что многие неоднократно сталкивались с необходимостью контролировать вводимый в TextBox текст. Чтобы не писать каждый раз однотипный код для проверки, можно воспользоваться следующей модификацией TextBox’а.
Необходим так же [CODEPOST ID=63]Design-time редактор для свойств типа enum с флагом Flags[/CODEPOST] |
| |
Разместить ссылку на этот исходник в форуме вы можете вставив в текст сообщения
следующую строку:
[CODEPOST ID=64]RegexTextBox: TextBox с маской по регулярному выражению[/CODEPOST] |
| Оценка: |
Проголосовало 13 посетителей, средняя оценка 4.62 |
| Оценить: |
|
1 using System;
2 using System.ComponentModel;
3 using System.Windows.Forms;
4 using System.Drawing.Design;
5 using System.Text.RegularExpressions;
6
7 namespace WandERRLib.Windows.Forms
8 {
9 /// <summary>
10 /// Пользовательский элемент управления, унаследованный от TextBox.
11 /// </summary>
12 public class RegexTextBox : System.Windows.Forms.TextBox
13 {
14 #region Переменные
15 private string regEx_ = String.Empty;
16 private RegexOptions regExOptions_ = RegexOptions.None;
17 private bool shouldPass_ = false;
18 #endregion
19
20 #region Конструкторы и деструкторы
21 /// <summary>
22 /// Конструктор по умолчанию.
23 /// Вызывает конструктор базового типа TextBox.
24 /// </summary>
25 public RegexTextBox() : base() { }
26 #endregion
27
28 #region Методы
29 private bool CanRemoveText()
30 {
31 bool result = (this.regEx_ == String.Empty);
32
33 if(!result)
34 {
35 try
36 {
37 Regex r = new Regex(this.regEx_, this.regExOptions_);
38 string testedString = this.Text.Remove(this.SelectionStart, this.SelectionLength);
39 Match m = r.Match(testedString);
40
41 result = m.Success;
42 }
43 catch(ArgumentException) {}
44 }
45
46 return result;
47 }
48
49 private bool CanInsertClipboardText()
50 {
51 bool result = (this.regEx_ == String.Empty);
52
53 if(!result)
54 {
55 try
56 {
57 IDataObject iData = Clipboard.GetDataObject();
58
59 if(iData.GetDataPresent(DataFormats.Text) || iData.GetDataPresent(DataFormats.UnicodeText))
60 {
61 Regex r = new Regex(this.regEx_, this.regExOptions_);
62 string testedString = this.Text.Remove(this.SelectionStart, this.SelectionLength).Insert(
63 this.SelectionStart,
64 (String) iData.GetData(iData.GetDataPresent(DataFormats.Text) ? DataFormats.Text : DataFormats.UnicodeText));
65 Match m = r.Match(testedString);
66
67 result = m.Success;
68 }
69 else
70 result = false;
71 }
72 catch {}
73 }
74
75 return result;
76 }
77
78 /// <summary>
79 /// Проверка на вставку текста из буфера,
80 /// нажатие клавиши Delete и других комбинаций клавиш.
81 /// </summary>
82 /// <param name="_e">объект с информацией о нажатых клавишах</param>
83 protected override void OnKeyDown(KeyEventArgs _e)
84 {
85 this.shouldPass_ = false;
86
87 base.OnKeyDown(_e);
88
89 if((_e.KeyCode == Keys.Delete)
90 && ((!_e.Control && !_e.Alt && !_e.Shift) || (_e.Shift && !_e.Alt && !_e.Control) || (_e.Control && !_e.Alt && !_e.Shift)))
91 {
92 // Проверка на нажатие комбинаций клавиш вместе с Delete
93 if(this.SelectionLength > 0)
94 {
95 _e.Handled = !this.CanRemoveText();
96 }
97 }
98
99 if(_e.Control && !_e.Alt && !_e.Shift)
100 {
101 // Проверка на нажатие комбинаций клавиш вместе с Control
102 this.shouldPass_ = (_e.KeyCode == Keys.Z) || (_e.KeyCode == Keys.C);
103
104 if(_e.KeyCode == Keys.V)
105 {
106 this.shouldPass_ = this.CanInsertClipboardText();
107 _e.Handled = !this.shouldPass_;
108 }
109 else if(_e.KeyCode == Keys.X)
110 {
111 this.shouldPass_ = this.CanRemoveText();
112 _e.Handled = !this.shouldPass_;
113 }
114 }
115 else if(_e.Shift && !_e.Alt && !_e.Control)
116 {
117 // Проверка на нажатие комбинаций клавиш вместе с Shift
118 if(_e.KeyCode == Keys.Insert)
119 {
120 this.shouldPass_ = this.CanInsertClipboardText();
121 _e.Handled = !this.shouldPass_;
122 }
123 }
124 }
125
126 /// <summary>
127 /// Проверка на соотвествие вводимого текста заданному регулярному выражению.
128 /// </summary>
129 /// <param name="_e">объект с информацией о введенном символе</param>
130 protected override void OnKeyPress(KeyPressEventArgs _e)
131 {
132 base.OnKeyPress(_e);
133
134 if(!this.shouldPass_ && this.IsInputChar(_e.KeyChar) && (this.regEx_ != String.Empty))
135 {
136 try
137 {
138 Regex r = new Regex(this.regEx_, this.regExOptions_);
139 string testedString = this.Text.Remove(this.SelectionStart, this.SelectionLength);
140 if(_e.KeyChar != '\b')
141 testedString = testedString.Insert(this.SelectionStart, _e.KeyChar.ToString());
142 else if((this.SelectionLength == 0) && (this.SelectionStart > 0))
143 {
144 testedString = testedString.Remove(this.SelectionStart - 1, 1);
145 }
146 Match m = r.Match(testedString);
147
148 if(!m.Success)
149 _e.Handled = true;
150 }
151 catch(ArgumentException) {}
152 }
153 }
154
155 #endregion
156
157 #region Свойства
158 /// <summary>
159 /// Регулярное выражение для проверки вводимого текста.
160 /// </summary>
161 [Category("Behavior"),
162 DefaultValue(""),
163 Description("Регулярное выражение для проверки вводимого текста.")]
164 public string RegEx
165 {
166 get { return this.regEx_; }
167
168 set { if(value != null) this.regEx_ = value; }
169 }
170
171 /// <summary>
172 /// Настройки для работы с регулярным выражением.
173 /// </summary>
174 [Category("Behavior"),
175 DefaultValue(RegexOptions.None),
176 Editor(typeof(Utils.FlagsEnumEditor), typeof(UITypeEditor)),
177 Description("Настройки для работы с регулярным выражением.")]
178 public RegexOptions RegexOptions { get { return this.regExOptions_; } set { this.regExOptions_ = value; } }
179 #endregion
180 }
181 }
182 |
| Вернуться к списку исходников в категории Winforms |
|
|
 |
 |
 |
 |
|
|