可自定义补全算法的TextBox控件
.NET framework中System.Windows.Froms.TextBox有补全功能,但只有有限的几种模式。如果想输入拼音,补全列表提示汉字,这是做不到的。于是,你可以使用我的CustomizableCompleteTextBox。
该控件的一个重要成员是Completing事件。你可以订阅此事件,在此事件中根据Text计算补全条目。
以下是一个拼音补全的示例。你需下载Microsoft Visual Studio International Pack v1.0,并引用其中的ChnCharInfo.dll。
private readonly string[] names = new[] { "孙权", "黄忠", "吕布", "马超", "魏延", "孙尚香", "卧龙诸葛亮", "吕蒙", "张角", "曹仁", "曹操", "吕布", "司马懿", "小乔", "张辽", "袁绍", "刘备", "夏侯渊", "诸葛亮", "貂蝉", "大乔", "关羽", "赵云" }; private void pinyinCompleteTextBox_Completing(object sender, CompletingEventArgs e) { string fullText = pinyinCompleteBox.Text; e.CompletingList.Clear(); foreach (var hero in names) { for (int i = 0; i < fullText.Length; i++) { if (hero.Length <= i) goto Out; //名字不够长 if (hero[i] == fullText[i]) //相同,继续看 continue; else //看看keyChar是不是这个字的拼音。 { ChineseChar cc = new ChineseChar(hero[i]); for (int j = 0; j < cc.PinyinCount; j++) { if (cc.Pinyins[j][0] == char.ToUpper(fullText[i])) goto HasShengmu; } goto Out; HasShengmu: continue; } } //比较了每个字,都没有跳出 e.CompletingList.Add(hero); Out: continue; } }
效果如下
以下是一个文件路径补全的示例。
public Form1() { InitializeComponent(); pathCompleteBox.TriggerChars.Add('//'); pathCompleteBox.CommitChars.Add('//'); } private void pathCompleteBox_Completing(object sender, CompletingEventArgs e) { string dir = pathCompleteBox.Text.Substring(0, pathCompleteBox.Text.LastIndexOf('//') + 1); e.CompletingList.Clear(); if (Directory.Exists(dir)) { DirectoryInfo di = new DirectoryInfo(dir); string filePart; if (dir.Length < pathCompleteBox.Text.Length) filePart = pathCompleteBox.Text.Substring(dir.Length); else filePart = string.Empty; foreach (var file in di.GetFiles()) e.CompletingList.Add(file.FullName); foreach (var directory in di.GetDirectories()) e.CompletingList.Add(directory.FullName); int index = 0; while (index < e.CompletingList.Count) { if (filePart.Length > 0 && e.CompletingList[index].StartsWith(Path.Combine(dir, filePart), StringComparison.OrdinalIgnoreCase) == false) e.CompletingList.RemoveAt(index--); index++; } e.PreferedItemIndex = 0; } }
效果如下。左图是CustomizableCompleteTextBox控件,右图是TextBox控件。