Winform 当我输入@时我想让后面有@163.com等后缀提示
时间: 2024-01-21 21:17:39 浏览: 34
你可以使用 AutoCompleteMode 属性来实现这个功能。下面是一些示例代码:
1. 首先,在你的 Winform 窗体中添加一个 TextBox 控件。
2. 在窗体的 Form_Load 事件中添加以下代码:
```
private void Form_Load(object sender, EventArgs e)
{
// 设置 TextBox 的 AutoCompleteMode 属性为 Append。
textBox1.AutoCompleteMode = AutoCompleteMode.Append;
// 创建一个 AutoCompleteStringCollection 对象,并添加一些后缀。
AutoCompleteStringCollection suffixes = new AutoCompleteStringCollection();
suffixes.AddRange(new string[] { "@163.com", "@gmail.com", "@hotmail.com" });
// 将 AutoCompleteStringCollection 对象赋值给 TextBox 的 AutoCompleteCustomSource 属性。
textBox1.AutoCompleteCustomSource = suffixes;
}
```
3. 然后,在 TextBox 的 TextChanged 事件中添加以下代码:
```
private void textBox1_TextChanged(object sender, EventArgs e)
{
// 获取 TextBox 中的文本。
string text = textBox1.Text;
// 如果文本中包含 @ 符号,则根据已经添加的后缀来提示用户。
if (text.Contains("@"))
{
string suffix = text.Substring(text.LastIndexOf("@"));
int index = textBox1.SelectionStart - suffix.Length;
// 如果用户在 @ 符号之后输入了其他文本,则不会出现自动提示。
if (index >= 0)
{
string prefix = text.Substring(0, index);
string[] suggestions = textBox1.AutoCompleteCustomSource.Cast<string>()
.Where(s => s.StartsWith(suffix))
.Select(s => prefix + s)
.ToArray();
if (suggestions.Length > 0)
{
string suggestion = suggestions[0];
textBox1.Text = suggestion;
textBox1.SelectionStart = suggestion.Length;
textBox1.SelectionLength = 0;
}
}
}
}
```
这样,当用户在 TextBox 中输入 @ 符号时,就会出现自动提示。用户可以使用方向键或鼠标来选择自动提示中的内容,或者继续输入其他文本。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)