using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using Microsoft.Win32; namespace Common { public partial class ComboBoxEx : ComboBox { public string RegSubKey; public int MaxHistoryCount; public ComboBoxEx() { InitializeComponent(); RegSubKey = Name; MaxHistoryCount = 20; } public void UpdateHistory() { if (Text.Trim() != "") { BeginUpdate(); try { string previousText = Text; int index = Items.IndexOf(Text); if (index >= 0) Items.RemoveAt(index); Text = previousText; Items.Insert(0, previousText); while (Items.Count > MaxHistoryCount) Items.RemoveAt(Items.Count - 1); } finally { EndUpdate(); } } } public void LoadFromRegistry() { RegistryKey regKey = Application.UserAppDataRegistry.OpenSubKey(RegSubKey) ?? Application.UserAppDataRegistry.CreateSubKey(RegSubKey); int count = regKey.GetValueInt("Count", 0); BeginUpdate(); try { while (Items.Count > count) Items.RemoveAt(Items.Count - 1); while (Items.Count < count) Items.Add(""); for (int i = 0; i < count; i++) { Items[i] = (string)regKey.GetValue(i.ToString(), ""); } } finally { EndUpdate(); } } public void SaveToRegistry() { RegistryKey regKey = Application.UserAppDataRegistry.OpenSubKey(RegSubKey, true) ?? Application.UserAppDataRegistry.CreateSubKey(RegSubKey); int i = 0; regKey.SetValue("Count", Items.Count); foreach (var item in Items) { regKey.SetValue(i.ToString(), item); i++; } while (true) { List names = regKey.GetValueNames().ToList(); if (names.IndexOf(i.ToString()) != -1) { regKey.DeleteValue(i.ToString()); } else break; i++; } } } }