开发一个可以记住最后输入的 x 个条目的文本框的最佳方法是什么?这是一个用 C# 编写的独立应用程序。

有帮助吗?

解决方案

@伊森

我忘记了您想要保存它的事实,因此这不是每个会话唯一的事情:P但是,是的,您是完全正确的。

这很容易完成,特别是因为它只是基本字符串,只需将 AutoCompleteCustomSource 的内容从 TextBox 写到文本文件中,在单独的行上即可。

我有几分钟的时间,所以我写了一个完整的代码示例...我以前会这样做,因为我总是尝试展示代码,但没有时间。不管怎样,这就是全部内容(减去设计器代码)。

namespace AutoComplete
{
    public partial class Main : Form
    {
        //so you don't have to address "txtMain.AutoCompleteCustomSource" every time
        AutoCompleteStringCollection acsc;
        public Main()
        {
            InitializeComponent();

            //Set to use a Custom source
            txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource;
            //Set to show drop down *and* append current suggestion to end
            txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            //Init string collection.
            acsc = new AutoCompleteStringCollection();
            //Set txtMain's AutoComplete Source to acsc
            txtMain.AutoCompleteCustomSource = acsc;
        }

        private void txtMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //Only keep 10 AutoComplete strings
                if (acsc.Count < 10)
                {
                    //Add to collection
                    acsc.Add(txtMain.Text);
                }
                else
                {
                    //remove oldest
                    acsc.RemoveAt(0); 
                    //Add to collection
                    acsc.Add(txtMain.Text);
                }
            }
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            //open stream to AutoComplete save file
            StreamWriter sw = new StreamWriter("AutoComplete.acs");

            //Write AutoCompleteStringCollection to stream
            foreach (string s in acsc)
                sw.WriteLine(s);

            //Flush to file
            sw.Flush();

            //Clean up
            sw.Close();
            sw.Dispose();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            //open stream to AutoComplete save file
            StreamReader sr = new StreamReader("AutoComplete.acs");

            //initial read
            string line = sr.ReadLine();
            //loop until end
            while (line != null)
            {
                //add to AutoCompleteStringCollection
                acsc.Add(line);
                //read again
                line = sr.ReadLine();
            }

            //Clean up
            sr.Close();
            sr.Dispose();
        }
    }
}

该代码将完全按原样工作,您只需创建带有名为 txtMain 的文本框的 GUI,并将 KeyDown、Closed 和 Load 事件连接到 TextBox 和主窗体。

另请注意,对于此示例并为了简单起见,我只是选择检测按下的 Enter 键作为将字符串保存到集合中的触发器。根据您的需要,可能有更多/不同的活动会更好。

同样,用于填充该集合的模型不是很“聪明”。当集合达到10的极限时,它只是删除最古老的字符串。这可能并不理想,但适用于示例。您可能需要某种评级系统(特别是如果您真的希望它像 Google 那样)

最后一点,建议实际上会按照它们在集合中的顺序显示。如果出于某种原因您希望它们以不同的方式显示,只需按您喜欢的方式对列表进行排序即可。

希望有帮助!

其他提示

这实际上相当简单,特别是在显示“自动完成”部分方面。就记住最后 x 个条目而言,您只需决定您认为是已完成条目的特定事件(或多个事件)并将该条目写到列表中......准确地说,是 AutoCompleteStringCollection。

TextBox 类具有您需要的以下 3 个属性:

  • 自动完成自定义源
  • 自动完成模式
  • 自动完成源

将 AutoCompleteMode 设置为 SuggestAppend,将 AutoCompleteSource 设置为 CustomSource。

然后在运行时,每次创建新条目时,请使用 AutoCompleteStringCollection 的 Add() 方法将该条目添加到列表中(如果需要,还可以弹出任何旧条目)。实际上,只要您已经初始化了 TextBox 的 AutoCompleteCustomSource 属性,您就可以直接对其进行此操作。

现在,每次您在文本框中键入内容时,它都会建议以前的条目:)

请参阅本文以获得更完整的示例: http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx

AutoComplete 还具有一些内置功能,例如文件系统和 URL(尽管它只执行在 IE 中输入的内容...)

我将完成列表存储在注册表中。

我使用的代码如下。它是可重复使用的,分三个步骤:

  1. 将这段代码中的命名空间和类名替换为您使用的任何名称。
  2. 在表单上调用 FillFormFromRegistry() 加载 事件,并调用 SaveFormToRegistry 闭幕式 事件。
  3. 将其编译到您的项目中。

您需要用两个属性来装饰程序集: [assembly: AssemblyProduct("...")][assembly: AssemblyCompany("...")] 。(这些属性通常在 Visual Studio 中创建的项目中自动设置,因此我不将此视为一个步骤。)

这种方式管理状态是完全自动的并且对用户透明。

您可以使用相同的模式来存储 WPF 或 WinForms 应用程序的任何类型的状态。比如文本框、复选框、下拉菜单的状态。你也可以 存储/恢复窗口的大小 - 非常方便 - 用户下次运行该应用程序时,它会在与关闭它时相同的位置和相同的大小打开。你可以 存储应用程序运行的次数. 。有很多可能性。

namespace Ionic.ExampleCode
{
    public partial class NameOfYourForm
    {
        private void SaveFormToRegistry()
        {
            if (AppCuKey != null)
            {
                // the completion list
                var converted = _completions.ToList().ConvertAll(x => x.XmlEscapeIexcl());
                string completionString = String.Join("¡", converted.ToArray());
                AppCuKey.SetValue(_rvn_Completions, completionString);
            }
        }

        private void FillFormFromRegistry()
        {
            if (!stateLoaded)
            {
                if (AppCuKey != null)
                {
                    // get the MRU list of .... whatever
                    _completions = new System.Windows.Forms.AutoCompleteStringCollection();
                    string c = (string)AppCuKey.GetValue(_rvn_Completions, "");
                    if (!String.IsNullOrEmpty(c))
                    {
                        string[] items = c.Split('¡');
                        if (items != null && items.Length > 0)
                        {
                            //_completions.AddRange(items);
                            foreach (string item in items)
                                _completions.Add(item.XmlUnescapeIexcl());
                        }
                    }

                    // Can also store/retrieve items in the registry for
                    //   - textbox contents
                    //   - checkbox state
                    //   - splitter state
                    //   - and so on
                    //
                    stateLoaded = true;
                }
            }
        }

        private Microsoft.Win32.RegistryKey AppCuKey
        {
            get
            {
                if (_appCuKey == null)
                {
                    _appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegistryPath, true);
                    if (_appCuKey == null)
                        _appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegistryPath);
                }
                return _appCuKey;
            }
            set { _appCuKey = null; }
        }

        private string _appRegistryPath;
        private string AppRegistryPath
        {
            get
            {
                if (_appRegistryPath == null)
                {
                    // Use a registry path that depends on the assembly attributes,
                    // that are presumed to be elsewhere. Example:
                    // 
                    //   [assembly: AssemblyCompany("Dino Chiesa")]
                    //   [assembly: AssemblyProduct("XPathVisualizer")]

                    var a = System.Reflection.Assembly.GetExecutingAssembly();
                    object[] attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true);
                    var p = attr[0] as System.Reflection.AssemblyProductAttribute;
                    attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), true);
                    var c = attr[0] as System.Reflection.AssemblyCompanyAttribute;

                    _appRegistryPath = String.Format("Software\\{0}\\{1}",
                                                     p.Product, c.Company);
                }
                return _appRegistryPath;
            }
        }

        private Microsoft.Win32.RegistryKey _appCuKey;
        private string _rvn_Completions = "Completions";
        private readonly int _MaxMruListSize = 14;
        private System.Windows.Forms.AutoCompleteStringCollection _completions;
        private bool stateLoaded;
    }

    public static class Extensions
    {
        public static string XmlEscapeIexcl(this String s)
        {
            while (s.Contains("¡"))
            {
                s = s.Replace("¡", "&#161;");
            }
            return s;
        }
        public static string XmlUnescapeIexcl(this String s)
        {
            while (s.Contains("&#161;"))
            {
                s = s.Replace("&#161;", "¡");
            }
            return s;
        }

        public static List<String> ToList(this System.Windows.Forms.AutoCompleteStringCollection coll)
        {
            var list = new List<String>();
            foreach (string  item in coll)
            {
                list.Add(item);
            }
            return list;
        }
    }
}

有些人 避免使用注册表来存储状态, ,但我发现这真的很简单又方便。如果您愿意,您可以非常轻松地构建一个安装程序,在卸载时删除所有注册表项。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top